Ejemplo n.º 1
0
 def Find( attribute ):
     """ Search for methods and attributes """
     print( "\nSearching for attribute '{}'...".format( attribute ) )
     found = False
     AA = attribute.upper()
     for thing in dir(Sword):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in Sword".format( thing ) ); found = True
     for thing in dir(Sword.SWVersion()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWVersion".format( thing ) ); found = True
     for thing in dir(Sword.SWMgr()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWMgr".format( thing ) ); found = True
     module = library.getModule( "KJV" )
     for thing in dir(module):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWModule".format( thing ) ); found = True
     for thing in dir(Sword.SWKey()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWKey".format( thing ) ); found = True
     for thing in dir(Sword.VerseKey()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in VerseKey".format( thing ) ); found = True
     #for thing in dir(Sword.InstallMgr()):
         #BB = thing.upper()
         #if BB.startswith(AA): print( "  Have {} in InstallMgr".format( thing ) ); found = True
     for thing in dir(Sword.LocaleMgr()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in LocaleMgr".format( thing ) ); found = True
     for thing in dir(Sword.SWFilterMgr()):
         BB = thing.upper()
         if BB.startswith(AA): print( "  Have {} in SWFilterMgr".format( thing ) ); found = True
     if not found: print( " Sorry, '{}' not found.".format( attribute ) )
Ejemplo n.º 2
0
    def get_text(self, key):
        """ Get the text at the given key in the module.
        i.e. get_text('3778') returns the greek strongs.

        """

        encoding = get_encoding()
        self._module.setKey(Sword.SWKey(key.encode('utf8')))
        item_text = self._module.renderText()
        # Make the text printable.
        # item_text = item_text.encode(encoding, 'replace')
        # item_text = item_text.decode(encoding, 'replace')
        return fill(item_text, screen_size()[1])
Ejemplo n.º 3
0
    def get_raw_text(self, key):
        """ Get the text at the given key in the module.
        i.e. get_text('3778') returns the greek strongs.

        """

        encoding = get_encoding()
        self._module.setKey(Sword.SWKey(key.encode('utf-8')))
        item_text = self._module.getRawEntry()

        # Make the text printable.
        # item_text = item_text.encode(encoding, 'replace')
        # item_text = item_text.decode(encoding, 'replace')
        return item_text
Ejemplo n.º 4
0
def _sword_bible_search(unicode_key_search):
    bible = BIBLE_CONFIG['default_bible']
    locale = BIBLE_CONFIG['default_locale']

    str_key_search = to_str(unicode_key_search)

    try:
        library = sw.SWMgr()
        bible_module = library.getModule(bible)
        key_module = sw.SWKey(str_key_search)
        key_module.setLocale(locale)
        bible_module.setKey(key_module)

        unicode_bible_name = bible
        unicode_module_text = to_unicode(bible_module.getRawEntry())
        unicode_key_name = to_unicode(bible_module.getKeyText())

    except Exception, e:
        raise BibleError(e)
Ejemplo n.º 5
0
def prepareDeckfor(bookAbbr, moduleStr, strongMod, langFont, langAlign,
                   dataDic):
    print("Generating a deck for {} ".format(bookAbbr))
    tmpDic = {}
    tmpDic['moduleName'] = moduleStr
    tmpDic['bookName'] = bookAbbr
    tmpDic['nameDic'] = {}
    tmpDic['nameTotalCnt'] = {}
    tmpDic['chapterDic'] = {}
    tmpDic['verseKeyDic'] = {}
    tmpDic = fillDicForBook(moduleStr, bookAbbr, tmpDic)
    #print(tmpDic)
    dataDic[moduleStr][bookAbbr] = tmpDic
    print("Info fetched, let s build the deck now")
    nameDic = dataDic[moduleStr][bookAbbr]["nameDic"]
    nameTotalCntDic = dataDic[moduleStr][bookAbbr]["nameTotalCnt"]
    chapterDic = dataDic[moduleStr][bookAbbr]["chapterDic"]
    verseKeyDic = dataDic[moduleStr][bookAbbr]["verseKeyDic"]
    deckTitle = "Vocabulary for {}".format(
        getInfoBasedOnAbbr(bookAbbr)["name"])
    #modelID=random.randrange(1 << 30, 1 << 31)
    #Let s keep this modlId once and for all.
    #We use the moduleStr so each book of a given module will use the same model in each deck.
    #modelID=hash(moduleStr)
    t_module = moduleStr.encode('utf8')
    module_hash = hashlib.sha256(t_module)
    modelID = int(module_hash.hexdigest(), base=16) % 100000000
    #deckID=random.randrange(1 << 30, 1 << 31)
    #deckID=hash(bookAbbr+moduleStr)
    t_deck_str = bookAbbr + moduleStr
    t_deck = t_deck_str.encode('utf8')
    deck_hash = hashlib.sha256(t_deck)
    deckID = int(deck_hash.hexdigest(), base=16) % 100000000
    #deckID=base64.b64encode( bytes(bookAbbr+moduleStr, "utf-8") )
    my_model = getNewAnkiModel(modelID, langFont, langAlign, moduleStr,
                               bookAbbr)
    my_deck = genanki.Deck(deckID, deckTitle)

    for strK in sorted(nameTotalCntDic,
                       key=nameTotalCntDic.__getitem__,
                       reverse=True):
        print("({}) {} occurence in total of {}".format(
            bookAbbr, nameTotalCntDic[strK], strK))
        #some sample sentences.
        sampleSentences = getSampleSentences(moduleStr, bookAbbr, strK)
        sampleHtml = ""
        for snt in sampleSentences:
            sampleHtml += "<br>"
            sampleHtml += snt

        #all the variants of the words i this book.
        allVariants = ""
        for c in nameDic[strK]:
            allVariants += c
            allVariants += " "
        #The actual Strongs entry
        library = Sword.SWMgr()
        target = library.getModule(strongMod)
        if not target:
            print("No module found")
            sys.exit()
        vk = Sword.SWKey(strK[1:])
        target.setKey(vk)
        #print("VK=",vk)
        #try:
        strongEntry = target.renderText().getRawData()
        #except:
        #    help(target.renderText())
        #    sys.exit()
        strongEntry = strongEntry.replace("\n", "<br />\n")
        if not isinstance(strongEntry, str):
            print("ke passa")
            help(strongEntry)
            sys.exit()
        #The tags.
        curTag = []
        for c in chapterDic[strK]:
            formatChapter = format(c, "03d")
            curTag.append("{}-chapter-{}".format(bookAbbr, formatChapter))
        for s in verseKeyDic[strK]:
            curTag.append(s)

        #Let s create the actual note.
        question = allVariants
        question += "<div id='sample' class=bibleQuote>"
        question += sampleHtml
        question += "</div>"
        answer = strongEntry
        #answer="KIKOOO"
        datetime = str(time.time())
        my_note = MyNote(model=my_model,
                         fields=[
                             question, answer, strK,
                             str(nameTotalCntDic[strK]), moduleStr, bookAbbr,
                             deckVersion, datetime
                         ],
                         tags=curTag)
        my_deck.add_note(my_note)
    #genanki.Package(my_deck).write_to_file('{}-{}.apkg'.format(bookAbbr,deckVersion))
    deckFileName = getDeckFileName(bookAbbr, deckVersion)
    genanki.Package(my_deck).write_to_file(deckFileName)
    print("modelid=", modelID)
    return
Ejemplo n.º 6
0
        if strKey not in nameDic.keys():
            nameTotalCnt[strKey] = 1
            nameDic[strKey] = []
            nameDic[strKey].append(fullWord)
        else:
            nameTotalCnt[strKey] = nameTotalCnt[strKey] + 1
            if fullWord not in nameDic[strKey]:
                nameDic[strKey].append(fullWord)

for strK in sorted(nameTotalCnt, key=nameTotalCnt.__getitem__, reverse=True):
    print

    print("{} occurence in total".format(nameTotalCnt[strK]))

    allVariants = b"Variants: "
    for c in nameDic[strK]:
        allVariants += c.encode('utf-8').strip() + b" "
    print(allVariants.decode('utf-8'))
    markup = Sword.MarkupFilterMgr(Sword.FMT_HTML)
    markup.thisown = False
    library = Sword.SWMgr(markup)
    target = library.getModule(strongModuleStr)
    if not target:
        print("No module found")
        sys.exit()
    vk = Sword.SWKey(strK[1:])
    target.setKey(vk)
    print(target.renderText())

    print("################")
Ejemplo n.º 7
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Sword
import sys

markup = Sword.MarkupFilterMgr(Sword.FMT_HTML)
markup.thisown = False
library = Sword.SWMgr(markup)
target = library.getModule("StrongsHebrew")
if not target:
    print "No module found"
    sys.exit()

vk = Sword.SWKey("05975")
target.setKey(vk)
print target.renderText()
Ejemplo n.º 8
0
def demo():
    """
    Sword
    """
    if Globals.verbosityLevel > 0: print( ProgNameVersion )

    #print( "\ndir Sword", dir(Sword) )

    if SwordType == "CrosswireLibrary":
        print( "\ndir Sword.SWVersion()", dir(Sword.SWVersion()) )
        print( "Version", Sword.SWVersion().getText() )
        print( "Versions", Sword.SWVersion().major, Sword.SWVersion().minor, Sword.SWVersion().minor2, Sword.SWVersion().minor3 ) # ints

        library = Sword.SWMgr()
        #print( "\ndir library", dir(library) )
        #print( "\nlibrary getHomeDir", library.getHomeDir().getRawData() )

    def Find( attribute ):
        """ Search for methods and attributes """
        print( "\nSearching for attribute '{}'...".format( attribute ) )
        found = False
        AA = attribute.upper()
        for thing in dir(Sword):
            BB = thing.upper()
            if BB.startswith(AA): print( "  Have {} in Sword".format( thing ) ); found = True
        for thing in dir(Sword.SWVersion()):
            BB = thing.upper()
            if BB.startswith(AA): print( "  Have {} in SWVersion".format( thing ) ); found = True
        for thing in dir(Sword.SWMgr()):
            BB = thing.upper()
            if BB.startswith(AA): print( "  Have {} in SWMgr".format( thing ) ); found = True
        module = library.getModule( "KJV" )
        for thing in dir(module):
            BB = thing.upper()
            if BB.startswith(AA): print( "  Have {} in SWModule".format( thing ) ); found = True
        for thing in dir(Sword.SWKey()):
            BB = thing.upper()
            if BB.startswith(AA): print( "  Have {} in SWKey".format( thing ) ); found = True
        for thing in dir(Sword.VerseKey()):
            BB = thing.upper()
            if BB.startswith(AA): print( "  Have {} in VerseKey".format( thing ) ); found = True
        #for thing in dir(Sword.InstallMgr()):
            #BB = thing.upper()
            #if BB.startswith(AA): print( "  Have {} in InstallMgr".format( thing ) ); found = True
        for thing in dir(Sword.LocaleMgr()):
            BB = thing.upper()
            if BB.startswith(AA): print( "  Have {} in LocaleMgr".format( thing ) ); found = True
        for thing in dir(Sword.SWFilterMgr()):
            BB = thing.upper()
            if BB.startswith(AA): print( "  Have {} in SWFilterMgr".format( thing ) ); found = True
        if not found: print( " Sorry, '{}' not found.".format( attribute ) )
    # end of Find

    if 0: # Install manager
        print( "\nINSTALL MANAGER" )
        im = Sword.InstallMgr() # FAILS
        print( "\ndir im", im, dir(im) )

    if 0: # Locale manager
        print( "\nLOCALE MANAGER" )
        lm = Sword.LocaleMgr()
        print( "dir lm", lm, dir(lm) )
        print( "default {}".format( lm.getDefaultLocaleName() ) )
        print( "available {}".format( lm.getAvailableLocales() ) ) # Gives weird result: "available ()"
        print( "locale {}".format( lm.getLocale( "en" ) ) ) # Needs a string parameter but why does it return None?

    if 0: # try filters
        print( "\nFILTER MANAGER" )
        fm = Sword.SWFilterMgr()
        print( "\ndir filters", dir(fm) )

    if SwordType == "CrosswireLibrary":
        # Get a list of available module names and types
        print( "\n{} modules are installed.".format( len(library.getModules()) ) )
        for j,moduleBuffer in enumerate(library.getModules()):
            moduleID = moduleBuffer.getRawData()
            module = library.getModule( moduleID )
            if 0:
                print( "{} {} ({}) {} '{}'".format( j, module.getName(), module.getType(), module.getLanguage(), module.getEncoding() ) )
                try: print( "    {} '{}' {} {}".format( module.getDescription(), module.getMarkup(), module.getDirection(), "" ) )
                except UnicodeDecodeError: print( "   Description is not Unicode!" )
        #print( "\n", j, "dir module", dir(module) )

        # Try some modules
        mod1 = library.getModule( "KJV" )
        print( "\nmod1 {} ({}) '{}'".format( mod1.getName(), mod1.getType(), mod1.getDescription() ) )
        mod2 = library.getModule( "ASV" )
        print( "\nmod2 {} ({}) '{}'".format( mod2.getName(), mod2.getType(), mod2.getDescription() ) )
        mod3 = library.getModule( "WEB" )
        print( "\nmod3 {} ({}) '{}'".format( mod3.getName(), mod3.getType(), mod3.getDescription() ) )
        strongsGreek = library.getModule( "StrongsGreek" )
        print( "\nSG {} ({}) '{}'\n".format( strongsGreek.getName(), strongsGreek.getType(), strongsGreek.getDescription() ) )
        strongsHebrew = library.getModule( "StrongsHebrew" )
        print( "\nSH {} ({}) '{}'\n".format( strongsHebrew.getName(), strongsHebrew.getType(), strongsHebrew.getDescription() ) )
        print()

        # Try a sword key
        sk = Sword.SWKey( "H0430" )
        #print( "\ndir sk", dir(sk) )

        # Try a verse key
        vk = Sword.VerseKey( "Jn 3:16" )
        #print( "\ndir vk", dir(vk) )
        #print( "val", vk.validateCurrentLocale() ) # gives None
        print( "getInfo", vk.getLocale(), vk.getBookCount(), vk.getBookMax(), vk.getIndex(), vk.getVersificationSystem() )
        print( "getBCV {}({}/{}) {}/{}:{} in '{}'({})/{}".format( vk.getBookName(), vk.getBookAbbrev(), vk.getOSISBookName(), vk.getChapter(), vk.getChapterMax(), vk.getVerse(), repr(vk.getTestament()), vk.getTestamentIndex(), vk.getTestamentMax() ) )
        print( "getText {} {} {} {} '{}'".format( vk.getOSISRef(), vk.getText(), vk.getRangeText(), vk.getShortText(), vk.getSuffix() ) )
        #print( "bounds {} {}".format( vk.getLowerBound(), vk.getUpperBound() ) )

        if 0: # Set a filter HOW DO WE DO THIS???
            rFs = mod1.getRenderFilters()
            print( mod1.getRenderFilters() )
            mod1.setRenderFilter()

        print( "\n{} {}: {}".format( mod1.getName(), "Jonny 1:1", mod1.renderText( Sword.VerseKey("Jn 1:1") ) ) )
        mod1.increment()
        print( "\n{} {}: {}".format( mod1.getName(), mod1.getKey().getText(), mod1.stripText(  ) ) )
        mod1.increment()
        print( "\n{} {}: {}".format( mod1.getName(), mod1.getKey().getText(), mod1.renderText(  ) ) )
        print( "\n{} {}: {}".format( mod2.getName(), vk.getText(), mod2.renderText( vk ) ) )
        print( "\n{} {}: {}".format( mod3.getName(), vk.getText(), mod3.renderText( vk ) ) )
        print( "\n{} {}: {}".format( mod3.getName(), vk.getText(), mod3.renderText( vk ) ) )

        print( "\n{} {}: {}".format( strongsGreek.getName(), sk.getText(), strongsGreek.renderText( Sword.SWKey("G746") ) ) )
        print( "\n{} {}: {}".format( strongsHebrew.getName(), sk.getText(), strongsHebrew.renderText( sk ) ) )

        if 0: # Get all vernacular booknames
            # VerseKey vk; while (!vk.Error()) { cout << vk.getBookName(); vk.setBook(vk.getBook()+1); }
            vk = Sword.VerseKey()
            while vk.popError()=='\x00':
                print( "bookname", vk.getBookName() )
                booknumber = int( bytes( vk.getBook(),'utf-8' )[0] )
                vk.setBook( booknumber + 1 )

        if 0: # Get booknames by testament (from http://www.crosswire.org/wiki/DevTools:Code_Examples)
            vk = Sword.VerseKey()
            for t in range( 1, 2+1 ):
                vk.setTestament( t )
                for i in range( 1, vk.getBookMax()+1 ):
                    vk.setBook( i )
                    print( t, i, vk.getBookName() )

        # Try a tree key on a GenBook
        module = library.getModule( "Westminster" )
        print( "\nmodule {} ({}) '{}'".format( module.getName(), module.getType(), module.getDescription() ) )
        def getGenBookTOC( tk, parent ):
            if tk is None: # obtain one from the module
                tk = Sword.TreeKey_castTo( module.getKey() ) # Only works for gen books
            if tk and tk.firstChild():
                while True:
                    print( " ", tk.getText() )
                    # Keep track of the information for custom implementation
                    #Class *item = storeItemInfoForLaterUse(parent, text);
                    item = (parent) # temp ....................
                    if tk.hasChildren():
                        print( "  Getting children..." )
                        getGenBookTOC( tk, item )
                    if not tk.nextSibling(): break
        # end of getGenBookTOC
        getGenBookTOC( None, None )