示例#1
0
    def __init__(self, module_name='KJV', markup=Sword.FMT_PLAIN):
        """ Setup the module to look up information in.

        """

        markup = Sword.MarkupFilterMgr(markup)

        # We don't own this or it will segfault.
        markup.thisown = False
        self._library = Sword.SWMgr(markup)
        self._module = self._library.getModule(module_name)

        self._bold_regx = re.compile(r'<b>(\w+)</b>', re.I)
        self._italic_regx = re.compile(
            r'''
                            (?:<i>|<hi\s*type="italic">)
                            ([\w\s]+)(?:</i>|</hi>)
                            ''', re.I | re.X)
        self._br_regx = re.compile(r'(<br[\s]*/>|<lb/>)[\s]?', re.I)
        self._cleanup_regx = re.compile(r'<[^>]*>')
        self._brace_regx = re.compile(r'\{([\W]*)([\w]*)([\W]*)\}')
        self._parenthesis_regx = re.compile(r'\(([\W]*)([\w]*)([\W]*)\)')
        self._bracket_regx = re.compile(r'\[([\W]*)([\w ]*)([\W]*)\]')
        self._verse_ref_regx = re.compile(
            r'''
                            <scripRef[^>]*>
                            ([^<]*)
                            </scripRef>
                            ''', re.I)
示例#2
0
def search(query,moduleName="ESV2011",searchType=0):
    """
    -1 phrase
    -2 multiword
    -3 entryAttrib (eg. Word//Lemma./G1234/)  
    -4 lucene
     0 regex
    """
    out=[]



    markup=Sword.MarkupFilterMgr(Sword.FMT_PLAIN)
    markup.thisown=False
    mgr = Sword.SWMgr(markup)
    mgr.prefixPath = swordDir
    mgr.configPath = "%s/mods.d" % swordDir
    mod=mgr.getModule(moduleName)
    mgr.setGlobalOption("Greek Accents","Off")
    mgr.setGlobalOption("Hebrew Vowel Points","Off")

    res=mod.doSearch(query,searchType)

    for n in range(res.getCount()):
        out.append(res.getElement(n).getShortText())
    return out
示例#3
0
def display_verse(key,moduleName,outputType=Sword.FMT_PLAIN):
    vk=Sword.VerseKey(key)
    markup=Sword.MarkupFilterMgr(outputType)
    #markup=Sword.MarkupFilterMgr(Sword.FMT_HTML)
    markup.thisown=False
    mgr = Sword.SWMgr(markup)
    mgr.prefixPath = swordDir
    mgr.configPath = "%s/mods.d" % swordDir
    mod=mgr.getModule(moduleName)
    mod.setKey(vk)
    #Look in bindings/objc/src/SwordManager.h for the correct mapping between C++ define and python string.
    #you may also have to look into specific module code though such as src/modules/filters/osisxlit.cpp:       static const char oName[] = "Transliterated Forms";
    mgr.setGlobalOption("Strong's Numbers","Off")
    mgr.setGlobalOption("Cross-references","Off")
    mgr.setGlobalOption("Morpheme Segmentation","Off")
    mgr.setGlobalOption("Morphological Tags","Off")
    mgr.setGlobalOption("Lemmas","Off")
    mgr.setGlobalOption("Words of Christ in Red","Off")
    mgr.setGlobalOption("Textual Variants","Off")
    mgr.setGlobalOption("Word Javascript","Off")
    mgr.setGlobalOption("Transliterated Forms","Off")

    if not mod:
        print "No module"
        sys.exit()
    return mod.renderText()
示例#4
0
def show_available_modules():
    mgr = Sword.SWMgr()
    mgr.prefixPath = swordDir
    mgr.configPath = "%s/mods.d" % swordDir

    for m in mgr.getModules().values():
        print "%s -> %s "%(m.Name(),m.Description())
示例#5
0
 def __init__( self ):
     if SwordType == "CrosswireLibrary":
         self.library = Sword.SWMgr()
         #self.keyCache = {}
         #self.verseCache = {}
     else:
         self.library = SwordModules.SwordModules() # Loads all of conf files that it can find
示例#6
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 ) )
示例#7
0
def get_verse(bookStr,
              chapterInt,
              verseNbr,
              moduleName,
              outputType=Sword.FMT_PLAIN):
    markup = Sword.MarkupFilterMgr(outputType)
    markup.thisown = False
    mgr = Sword.SWMgr(markup)

    mod = mgr.getModule(moduleName)
    versification = mod.getConfigEntry("Versification")
    vk = Sword.VerseKey()
    vk.setVersificationSystem(versification)
    #vk.setTestament() ??
    vk.setBookName(bookStr)
    vk.setChapter(chapterInt)
    vk.setVerse(verseNbr)

    mod.setKey(vk)
    mgr.setGlobalOption("Hebrew Vowel Points", "On")

    if not mod:
        print("No module")
        sys.exit()

    return mod.renderText()
示例#8
0
def getBCV( BCV, moduleAbbreviation='KJV' ): # Very slow -- for testing only
    if Globals.debugFlag: print( "SwordResources.getBCV({},{})".format( BCV, moduleAbbreviation ) )
    library = Sword.SWMgr()
    module = library.getModule( moduleAbbreviation )
    refString = "{} {}:{}".format( BCV[0][:3], BCV[1], BCV[2] )
    #print( 'refString', refString )
    return module.stripText( Sword.VerseKey( refString ) )
示例#9
0
def getVerseMax(moduleName, bookName, chapterNbr):
    mgr = Sword.SWMgr()
    mod = mgr.getModule(moduleName)
    versification = mod.getConfigEntry("Versification")
    vk = Sword.VerseKey()
    vk.setVersificationSystem(versification)
    vk.setBookName(bookName)
    vk.setChapter(chapterNbr)
    return vk.getVerseMax()
示例#10
0
    def __init__(self,
                 reference_iter,
                 strongs=False,
                 morph=False,
                 module='KJV',
                 markup=Sword.FMT_PLAIN,
                 render=''):
        """ Initialize.

        """

        markup = Sword.MarkupFilterMgr(markup)

        # We don't own this or it will segfault.
        markup.thisown = False
        self._library = Sword.SWMgr(markup)
        self._library.setGlobalOption("Headings", "On")
        self._library.setGlobalOption("Cross-references", "Off")

        if strongs:
            self._library.setGlobalOption("Strong's Numbers", "On")
        else:
            self._library.setGlobalOption("Strong's Numbers", "Off")

        if morph:
            self._library.setGlobalOption("Morphological Tags", "On")
        else:
            self._library.setGlobalOption("Morphological Tags", "Off")

        # Strings for finding the heading.
        self._head_str = Sword.SWBuf('Heading')
        self._preverse_str = Sword.SWBuf('Preverse')
        self._canon_str = Sword.SWBuf('canonical')

        self._module = self._library.getModule(module)
        self._key = self._module.getKey()

        if render.lower() == 'raw':
            self._render_func = self._module.getRawEntry
        elif render.lower() == 'render_raw':
            self._fix_space_regx = re.compile(r'([^\.:\?!])\s+')
            self._fix_end_regx = re.compile(r'\s+([\.:\?!,;])')
            self._fix_start_tag_regx = re.compile(r'(<[npi]>)\s*')
            self._fix_end_tag_regx = re.compile(r'\s*(</[npi]>)')
            self._upper_divname_regx = re.compile(r'(\w+)([\'s]*)')
            self._render_func = \
                    lambda: self._parse_raw(self._module.getRawEntry(),
                                            strongs, morph)
        else:
            self._render_func = self._module.renderText

        self._ref_iter = reference_iter
示例#11
0
def getNbrChapter(moduleName, bookAbbr):
    mgr = Sword.SWMgr()
    mod = mgr.getModule(moduleName)
    versification = mod.getConfigEntry("Versification")
    vk = Sword.VerseKey()
    vk.setVersificationSystem(versification)
    targetBook = 0
    for curBook in getAllBooks(versification):
        if curBook["abbr"] == bookAbbr:
            targetBook = curBook
    nbrChapter = vk.chapterCount(targetBook['testament'],
                                 targetBook['bookCount'])
    return nbrChapter
示例#12
0
    def __init__(self, reference_iter: Iterator, module: str = 'KJV'):
        """Initialize the sword module."""
        # This doesn't matter.
        markup = Sword.MarkupFilterMgr(Sword.FMT_PLAIN)

        # We don't own this or it will segfault.
        markup.thisown = False
        self._library = Sword.SWMgr(markup)

        self._module = self._library.getModule(module)
        self._key = self._module.getKey()

        self._ref_iter = reference_iter

        self._fix_space_regx = re.compile(r'([^\.:\?!])\s+')
        self._fix_end_regx = re.compile(r'\s+([\.:\?!,;])')
        self._remove_tag_regx = re.compile(r'(<i>\s?|\s?</i>)')
        self._fix_start_tag_regx = re.compile(r'(<i>)\s*')
        self._fix_end_tag_regx = re.compile(r'\s*(</i>)')
示例#13
0
文件: bible.py 项目: xerp/projections
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)
示例#14
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("################")
示例#15
0
import logging
import threading
import re

from bs4 import BeautifulSoup

import Sword

from gi.repository import GLib

logger = logging.getLogger(__name__)

MODTYPE_BIBLES = Sword.SWMgr().MODTYPE_BIBLES
MODTYPE_GENBOOKS = Sword.SWMgr().MODTYPE_GENBOOKS

FMT_HTML = Sword.FMT_HTML
FMT_PLAIN = Sword.FMT_PLAIN
FMT_OSIS = Sword.FMT_OSIS

MARKUP = {"2TGreek": FMT_OSIS, "MorphGNT": FMT_HTML, "OSHB": FMT_HTML}

pattern_paragraph_range = re.compile(r'^(\d+) to (\d+)$')

class SwordLibrary():
    def __init__(self, markup = Sword.FMT_PLAIN):
        logger.debug("SwordLibrary - Create a new instance")
        self.markup = Sword.MarkupFilterMgr(markup)
        self.markup.thisown = False

        self.mgr = Sword.SWMgr(self.markup)
示例#16
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
示例#17
0
def getSampleSentences(moduleStr, bookAbbr, strK):
    #print("Need to find sample for {}".format(strK))
    out = []
    mgr = Sword.SWMgr()
    mod = mgr.getModule(moduleStr)

    query = "lemma:{}".format(strK)
    res = mod.doSearch(query, -4)

    bsmpl = []
    for n in range(res.getCount()):
        #res.getElement(n) is a SWKey
        vSnt = res.getElement(n).getShortText()
        #print(vSnt)
        if re.match(bookAbbr, vSnt):
            bsmpl.append(res.getElement(n).getShortText())

    maxSample = 4
    cnt = 1
    #rawHtml=[]
    sampleDIC = {}
    for v in bsmpl:
        #print("VERSE=",v)
        ma = re.match('^(\S+) (\d+):(\d+)', v)
        if ma:
            abbr = ma.group(1)
            chap = int(ma.group(2))
            vers = int(ma.group(3))
            #print(abbr,chap,vers)
            raw = get_verse(abbr,
                            chap,
                            vers,
                            moduleStr,
                            outputType=Sword.FMT_HTML)
            #rawHtml.append(raw.c_str())
            sampleDIC[v] = raw.c_str()
            if cnt > maxSample:
                break
            cnt += 1
        else:
            print("Not maching {}".format(v))
            sys.exit()

    for curK in sampleDIC.keys():
        r = sampleDIC[curK]
        #print("key",curK)
        #print("val=",r)
        #tmpHTML="<div id='sample' class=bibleQuote>"
        tmpHTML = ""
        soup = BeautifulSoup(r, features="html.parser")
        for w in soup.find_all('w'):
            pattern = re.compile(".*{}.*".format(strK), re.UNICODE)
            if pattern.match(w.decode()):
                tmpHTML += "<span class=targetWord>"
                tmpHTML += w.decode()
                tmpHTML += "</span>"
            else:
                tmpHTML += w.decode()
            tmpHTML += " "
        #tmpHTML+="</div>"
        #print( "\n\n<br>*********<br>\n")
        #print(curK)
        #print( r)
        #print( "<br>######<br>\n")
        #print(tmpHTML)

        #out.append("<H1>{}</H1>".format(curK)+tmpHTML)
        out.append(tmpHTML)

    return out
示例#18
0
    def __init__(self, markup = Sword.FMT_PLAIN):
        logger.debug("SwordLibrary - Create a new instance")
        self.markup = Sword.MarkupFilterMgr(markup)
        self.markup.thisown = False

        self.mgr = Sword.SWMgr(self.markup)
示例#19
0
    for i in range(1, 3):
        vk.setTestament(i)
        for j in range(1, vk.bookCount(i) + 1):
            vk.setBook(j)
            tmp = {}
            tmp['name'] = vk.bookName(i, j)
            tmp['abbr'] = vk.getBookAbbrev()
            tmp['testament'] = i
            tmp['bookCount'] = j
            out.append(tmp)
    return out


locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
moduleName = "FreCrampon"
outputType = Sword.FMT_PLAIN
markup = Sword.MarkupFilterMgr(outputType)
markup.thisown = False
mgr = Sword.SWMgr(markup)
mod = mgr.getModule(moduleName)
versification = mod.getConfigEntry("Versification")

config = Sword.SWConfig("/usr/share/sword/locales.d/abbr.conf")
config.get("Text", "Genesis")
getAllBooks(versification)

for book in getAllBooks(versification):
    name = book["name"]
    config = Sword.SWConfig("/usr/share/sword/locales.d/fr-utf8.conf")
    print("%s##%s" % (name, config.get("Text", name)))
示例#20
0
def test_modules_empty():
    mgr = Sword.SWMgr("/tmp")
    modules = mgr.getModules()
    assert modules.size() == 0
示例#21
0
    def installModule(self,
                      destMgr,
                      fromLocation,
                      modName,
                      install_source=None):
        """Install a module from destMgr to a location

		Returns -1 on aborted, 0 on success and 1 on error
		"""

        aborted = False
        cipher = False

        print destMgr, fromLocation, modName, install_source
        #printf("***** InstallMgr::installModule\n")

        #if fromLocation:
        #	printf("***** fromLocation: %s \n", fromLocation)

        #printf("***** modName: %s \n", modName)

        if install_source:
            sourceDir = self.privatePath + "/" + install_source.source
        else:
            sourceDir = fromLocation

        sourceDir = removeTrailingSlash(sourceDir)
        sourceDir += '/'

        # do this with False at the end to stop the augmenting
        mgr = Sword.SWMgr(sourceDir, True, None, False, False)

        module = mgr.config.getSections().find(Sword.SWBuf(modName))

        if module != mgr.config.getSections().end():
            mod_second = module.value()[1]

            entry = mod_second.find(Sword.SWBuf("CipherKey"))
            if entry != mod_second.end():
                cipher = True

            # This first check is a method to allow a module to specify each
            # file that needs to be copied
            file_buf = Sword.SWBuf("File")
            file_value = mod_second
            fileEnd = file_value.upper_bound(file_buf)
            fileBegin = file_value.lower_bound(file_buf)
            print fileEnd == fileBegin

            if (fileBegin != fileEnd):
                # copy each file
                if (install_source):
                    while (fileBegin != fileEnd):
                        swbuf = fileBegin.value()[1]
                        src = swbuf.c_str()
                        # ftp each file first
                        buffer = sourceDir + src
                        if self.ftpCopy(install_source, src, buffer):

                            aborted = True
                            break  # user aborted

                        fileBegin += 1

                    fileBegin = mod_second.lower_bound(file_buf)

                if not aborted:
                    # DO THE INSTALL
                    while fileBegin != fileEnd:
                        sourcePath = sourceDir
                        sourcePath += fileBegin.value()[1].c_str()
                        dest = destMgr.prefixPath
                        dest = removeTrailingSlash(dest)
                        dest += '/'
                        dest += fileBegin.value()[1].c_str()
                        FileMgr.copyFile(sourcePath, dest)

                        fileBegin += 1

                # ---------------

                if install_source:
                    fileBegin = mod_second.lower_bound(file_buf)
                    while (fileBegin != fileEnd):
                        # delete each tmp ftp file
                        buffer = sourceDir + fileBegin.value()[1].c_str()
                        FileMgr.removeFile(buffer.c_str())
                        fileBegin += 1

            # This is the REAL install code, the above code I don't think has
            # ever been used
            #
            # Copy all files in DataPath directory
            #
            else:

                entry = mod_second.find(Sword.SWBuf("AbsoluteDataPath"))
                if (entry != mod_second.end()):
                    absolutePath = entry.value()[1].c_str()
                    relativePath = absolutePath

                    entry = mod_second.find(Sword.SWBuf("PrefixPath"))
                    if (entry != mod_second.end()):
                        relativePath = relativePath[entry.value()[1].size():]
                    else:
                        relativePath = relativePath[len(mgr.prefixPath):]

                    printf("***** mgr.prefixPath: %s", mgr.prefixPath)
                    printf("***** destMgr.prefixPath: %s", destMgr.prefixPath)
                    printf("***** absolutePath: %s", absolutePath)
                    printf("***** relativePath: %s", relativePath)

                    if install_source:
                        if self.ftpCopy(install_source, relativePath,
                                        absolutePath, True):
                            aborted = True
                            # user aborted

                    if not aborted:
                        destPath = (destMgr.prefixPath or "") + relativePath
                        FileMgr.copyDir(absolutePath, destPath)

                    if install_source:
                        # delete tmp ftp files
                        mgr.deleteModule(modName)
                        FileMgr.removeDir(absolutePath)

            if not aborted:
                confDir = sourceDir + "mods.d/"
                try:
                    items = os.listdir(confDir)
                except OSError:
                    pass
                else:
                    for item in items:
                        modFile = confDir
                        modFile += item
                        config = Sword.SWConfig(modFile)
                        if config.getSections().find(Sword.SWBuf(modName)) != \
                         config.getSections().end():
                            targetFile = destMgr.configPath or ""  #; //"./mods.d/";
                            targetFile = removeTrailingSlash(targetFile)
                            targetFile += "/"
                            targetFile += item
                            FileMgr.copyFile(modFile, targetFile)
                            if (cipher):
                                if self.getCipherCode(modName, config):
                                    # An error has occurred with getting
                                    # cipher code
                                    # This removes the module
                                    # Is this wise?
                                    newDest = Sword.SWMgr(destMgr.prefixPath)
                                    self.removeModule(newDest, modName)
                                    aborted = True
                                else:
                                    config.Save()
                                    FileMgr.copyFile(modFile, targetFile)

                        del config

            if aborted:
                return -1

            return 0
        return 1
示例#22
0
"""
Methods to wrap the basic Sword library to be able to do quick and simple
Python style iterations of modules and the like
"""
from typing import Generator

# We disable the lint check on this, because this file is old and supports very
# old versions of Python, and also it needs the underlying C wrapper to work
# properly. And we don't want to have to run binary packages in lint
import Sword  # pylint: disable=import-error

mgr = Sword.SWMgr()


def get_mod(module: str) -> Sword.SWModule:
    """
    Simply grabs a module without the need to do more things to configure it
    than this.
    """
    mod = mgr.getModule(module)
    return mod


def strip_verses(module: Sword.SWModule) -> Generator[str, None, None]:
    """
    A generator to use that iterates verses and yields up the text of the
    verse stripped of formatting and markup.
    """
    # Create a new key at the start of the module
    key = module.createKey()
    key.setIndex(0)
示例#23
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 )