コード例 #1
0
 def __init__(self):
     self.metadata = metadata
     self.metadata.bind = SQLITE + PATH_TO_RES + DBNAME      
     self.frequency = FrequencyLookup()
     self.count = 0
コード例 #2
0
class DBoMagic:
    
    def __init__(self):
        self.metadata = metadata
        self.metadata.bind = SQLITE + PATH_TO_RES + DBNAME      
        self.frequency = FrequencyLookup()
        self.count = 0
        
    def setupDB(self):  
        """Initialize/read database on disk"""
#        self.db = SqlSoup(SQLITE + PATH_TO_RES + KANJIDIC2) 
        setup_all()
        if not os.path.exists(PATH_TO_RES + DBNAME):
            create_all()
             
        session.bind = metadata.bind
        #self.frequency.loadFrequencyDict()
    
    def getNextQuizItem(self):
        #TODO: implement with great verve and so on!
        #TODO: check if item.next_quiz is the same for multiple items
        #...
        return  Item.query.filter_by(current_session = True).order_by(asc(Item.next_quiz)).first()
        
    def initializeCurrentSession(self, sessionSize):
        
        selection = Item.query.filter_by(active = True).all()
            
        self.endCurrentSesion()
        n = sessionSize
        
        shuffle(selection)
        if n > len(selection) : n = len(selection)
        random_selection = sample(selection, n)

        for item in random_selection:
            # mark n random items as 'current' 
            item.current_session = True
            item.been_in_session = item.been_in_session + 1     #may be useful later on
            
        session.commit()

    def endCurrentSesion(self):
        for item in Item.query.all():
            item.current_session = False
        
        session.commit()

    def updateQuizItem(self, item):
        session.commit()
    
    def addItemToDb(self, item):
        if(len(Item.query.filter_by(item = item).all()) == 0):
            Item(item = item, tags = u'user', next_quiz = datetime.now(), leitner_grade = Leitner.grades.None.index, active = True, 
                                current_session = False, been_in_session = 0)
            session.commit()
            
    def addWordToDbByValue(self, item):
        if len(item) > 1:
            if(len(Item.query.filter_by(item = item).all()) == 0):
                Item(item = item, tags = u'user', next_quiz = datetime.now(), leitner_grade = Leitner.grades.None.index, active = True, 
                                    current_session = False, been_in_session = 0)
                session.commit()
        
#    def addSentenceToDb(self, kanji, sentence, translation):
#        Kanji.query.filter_by(character = kanji).one().example.append(Example(sentence = sentence,translation = translation))          #or get_by
#        #k.example.append(Example(sentence = sentence,translation = translation)) 
#        session.commit()
        
#    def addExamplesForKanji(self, kanji, examples):
#        for example in examples:
#            kanji.example.append(Example(sentence = example,translation = examples[example]))
#        session.commit()
            
#    def getExample(self, item):
#        examples = item.example
#        return examples[randrange(0, len(examples))]
        
#    def checkIfKanjiHasExamples(self, kanji):
#        if len(kanji.example) > 0:
#            return True
#        else:
#            return False
        
#    def findSimilarReading(self, kana):
#        """Generate quiz variants based on correct reading ('kana' argument)"""
#        
#        size = len(kana) - 1
#        readings = []
#        selection = []
#        count = 0
#        
#        if len(kana) > 1:
#            while True:
#                selection = self.db.kunyomi_lookup.filter(self.db.kunyomi_lookup.reading.like(kana[0] + u'_' * size)).all()
#            
#                if len(selection) >= 4:
#                    rand = sample(selection, 4)
#                    for read in rand:
#                        readings.append(read.reading)
#                        
#                else:
#                    perm = list(map(''.join, permutations(kana)))
#                    if len(perm) >= 4:
#                        readings = sample(perm, 4)
#                    else:
#                        i = 0; variant = u''
#                        while i < 4:
#                            j = 0
#                            while j < size:
#                                variant += KANA_TABLE[randrange(0, len(KANA_TABLE))];    j = j + 1
#                            readings.append(variant);   variant = u'';  i = i + 1
#                    
#                readings = removeDuplicates(readings)   
#                count = count + 1
#                
#                if len(readings) >= 4: break
#                if count > 3: break
#                
#        elif len(kana) == 1:
#            i = 0
#            while True:
#                for _ in repeat(None, 4):
#                    readings.append(KANA_TABLE[randrange(0, len(KANA_TABLE))]) 
#                readings = removeDuplicates(readings)   
#                if len(readings) >= 4: break
#                elif i < 4: i = i + 1
#                else: break
#                
#        #inserting correct reading at random position (if not already)
#        print ' '.join(readings) #THIS IS FOR TEST ONLY     
#        if kana not in readings[:4]:
#            if len(readings) >= 4:
#                readings[randrange(0, 4)] = kana
#            else:
#                readings[randrange(0, len(readings))] = kana
#        print ' '.join(readings) #THIS IS FOR TEST ONLY     
#
#        return readings
    
    def addItemsToDb(self, min, max, exact=False, tag='user'):
        self.count = 0
        success = False
        
        items = self.frequency.getFrequencyRange(min, max, exact)
        
        now = datetime.now()
        for item in items:
            if session.query(Item).filter_by(item = item).count()  == 0:
                Item(item = item.lower(), tags = tag, next_quiz = now, leitner_grade = Leitner.grades.None.index, active = True, 
                current_session = False, been_in_session = 0)
                
                self.count = self.count + 1
                success = True
                try: 
                    session.commit()
                except IntegrityError:
                    session.rollback()
                    success = False
        return success
    
    def countTotalItemsInDb(self):
        return { 'items' : Item.query.count() }
    
#    def countItemsByGrades(self):
#        results = {}
#        i = 1
#        jlpt = u'jlpt'
#        grade = u'grade'
#        
#        while True:    
#            results[jlpt + str(i)] = session.query(Kanji).filter(Kanji.tags.like(u'%' + jlpt + str(i) + '%' )).count()  
#            if i > 3 : break
#            else: i = i + 1
#        i = 1    
#        while True:
#            results[grade + str(i)] = session.query(Kanji).filter(Kanji.tags.like(u'%' + grade + str(i) + '%' )).count()
#            if i > 9 : break
#            else: i = i + 1
#            
#        return results
    
    def updateActive(self, criteria, flag):
        lookup = Item.query.filter(Item.tags.like(u'%' + criteria + '%' )).all()
        for item in lookup:
            item.active = flag
            
        session.commit()
        
    def checkIfActive(self, criteria):
        kanji = session.query(Item).filter(Item.tags.like(u'%' + criteria + '%' )).first()
        if kanji is not None:
            return kanji.active
        
    def getAllItemsInFull(self):
        return Item.query.all()
        
    def clearDB(self):
        Item.query.delete()
        session.commit()
        session.execute('VACUUM')