コード例 #1
0
    def GetChapter(self,
                   ref,
                   specialref="",
                   specialtemplate=None,
                   context="",
                   raw=False):
        self.vk.setText(to_str(ref, self.mod))

        #get first ref
        text = self.vk.getText()

        match = re.match("([\w\s]+) (\d+):(\d+)", text)
        if match:
            book, chapter, verse = match.group(1, 2, 3)

            # include introductions - book introduction if necessary
            ref = "%s %s" % (book, chapter)
            text = "%s %s:0-%s %s" % (book, chapter, book, chapter)
            vk = SW.VerseKey()
            vk.Headings(1)
            list = vk.ParseVerseList(text, "", True)
            if chapter == "1":
                vk.setText("%s 0:0" % book)
                list.add(vk)
                #text = "%s 0:0-%s %s" % (book, book, chapter)

                if book == "Genesis":
                    vk.Testament(0)
                    list.add(vk)
                    vk.Testament(1)
                    list.add(vk)

                elif book == "Matthew":
                    # set it to 0 first so that we come back to the testament
                    # heading
                    vk.Testament(0)
                    vk.Testament(2)
                    list.add(vk)

                list.sort()

        else:
            dprint(ERROR, "Couldn't parse verse text", text)
            return ""

        return self.GetReference(ref,
                                 specialref,
                                 specialtemplate,
                                 context,
                                 raw=raw,
                                 headings=True,
                                 verselist=list)
コード例 #2
0
ファイル: process_text.py プロジェクト: nognkantoor/bpbible
    def write_osis_ref(self, ref, node, si, parse_children):
        items = []
        cnt = 0
        for item in ref.split(" "):
            if "-" in item:
                assert item.count("-") == 1, item
                start, end = item.split("-")

                vk = SW.VerseKey(start, end)
                while vk.Error() == '\x00':
                    items.append(vk.getOSISRef())
                    vk.increment(1)
            else:
                items.append(item)

        refs = u' '.join(items)
        refs = refs.encode("utf8").replace(".", self.FIELD_SEPARATOR)
        self.write_field(node, si, fields.RefField, refs, parse_children)
コード例 #3
0
ファイル: index.py プロジェクト: nognkantoor/bpbible
                btext.append(a)
                seen.add(a)

            verses.update(spl)
    return [x for x in btext if x not in removals]


class SearchException(Exception):
    pass


class Cancelled(Exception):
    pass


vk = SW.VerseKey()


def printx(x):
    print x
    return True


class BadBook(Exception):
    def __init__(self, index, errors):
        errors = [
            _("A problem was detected with this book while indexing it:")
        ] + list(errors) + [
            '',
            _("Check whether there is a newer version of this book which "
              "might fix this problem.")
コード例 #4
0
ファイル: prep_texts.py プロジェクト: nognkantoor/bpbible
print module_dir		
result = driver.createModule(module_dir)
assert result == '\x00', \
	"Failed creating module"

		
module = driver(module_dir)
assert module.isWritable(), "MODULE MUST BE WRITABLE"


for key in keys:
	from swlib.pysw import VerseList
	key = VerseList(key)[0]
	lower_bound = key.LowerBound().getText()
	key_text = "This is %s." % key.getRangeText()
	module.setKey(SW.VerseKey(lower_bound))
	module.setEntry(key_text)
	for linked_key in [key_.getText() for key_ in key][1:]:
		module.setKey(SW.VerseKey(linked_key))
		module.linkEntry(SW.VerseKey(lower_bound))

conf_file = items["bible"][4]

f = open("mods.d/test_bad.conf", "w")
f.write(conf_file + "\ntest")
f.close()

zip = zipfile.ZipFile("test_bad.zip", "w")
zip.write("mods.d/test_bad.conf")
zip.close()
コード例 #5
0
    def GetReference_yield(self,
                           verselist,
                           max_verses=177,
                           raw=False,
                           stripped=False,
                           module=None,
                           exclude_topic_tag=None,
                           display_tags=True,
                           skip_linked_verses=True):
        """GetReference_yield: 
			yield the body dictionary and headings dictinoary
			for each reference.

		Preconditions:
			one of module or self.mod is not None
			verselist is valid"""
        #only for bible keyed books
        verselist.setPosition(TOP)
        verselist.Persist(1)
        u_vk = pysw.UserVK()
        u_vk.Headings(1)
        versekey = SW.VerseKey()
        versekey.Headings(1)
        mod = module or self.mod
        old_mod_skiplinks = mod.getSkipConsecutiveLinks()
        mod.setSkipConsecutiveLinks(True)
        mod.SetKey(verselist)
        verses_left = max_verses

        render_text, render_start, render_end = self.get_rendertext(mod)
        if render_start: render_start()

        try:
            incrementer = mod if skip_linked_verses else verselist
            while not self.has_error(incrementer):
                if verses_left == 0:
                    yield None, None
                    break

                if not skip_linked_verses:
                    mod.SetKey(verselist)
                key = mod.getKey()
                #versekey = VK.castTo(key)
                versekey.setText(key.getText())
                #if(self.headings):
                #	versekey.Headings(1)
                osisRef = versekey.getOSISRef()
                internal_reference = versekey.getText()

                rawentry = mod.getRawEntryBuf()
                if skip_linked_verses and not rawentry.length():
                    # don't include empty text; typically this may be at the
                    # start of the chapter or something...
                    incrementer.increment(1)
                    continue

                start_verse = end_verse = versekey.Verse()

                # look forwards and backwards to see what the linked verse
                # number is (e.g. 3-5). Note: currently this won't cross
                # chapter boundaries
                vk = versekey.clone()
                vk = versekey.castTo(vk)
                vk.thisown = True
                vk.Headings(0)
                while (vk.Error() == '\x00'
                       and vk.Chapter() == versekey.Chapter()
                       and mod.isLinked(vk, versekey)):
                    end_verse = vk.Verse()
                    vk.increment(1)

                vk.copyFrom(versekey)
                vk.Headings(0)

                # hopefully we won't see anything backwards, but it is
                # possible (i.e. if we start in the middle of a linked
                # verse
                while (vk.Error() == '\x00'
                       and vk.Chapter() == versekey.Chapter()
                       and mod.isLinked(vk, versekey)):
                    start_verse = vk.Verse()

                    vk.decrement(1)

                if start_verse == end_verse:
                    verse = "%d" % start_verse
                else:
                    verse = "%d-%d" % (start_verse, end_verse)

                u_vk.setText(internal_reference)
                if internal_reference.endswith(":0"):
                    if start_verse != end_verse:
                        print "WARNING: unhandled linked verse with verse 0"

                    if versekey.Chapter() == 0:
                        reference = u_vk.getBookName()
                    else:
                        reference = u_vk.get_book_chapter()

                else:
                    reference = u_vk.get_book_chapter()
                    reference += ":" + verse

                body_dict = dict(
                    # text comes later
                    versenumber=process_digits(verse, userOutput=True),
                    chapternumber=process_digits(str(versekey.Chapter()),
                                                 userOutput=True),
                    booknumber=ord(versekey.Book()),
                    bookabbrev=versekey.getBookAbbrev(),
                    bookname=versekey.getBookName(),
                    reference=reference,
                    internal_reference=internal_reference,
                    osisRef=osisRef,
                )

                # usually RenderText flushes this out, but we haven't called
                # that yet - but we definitely don't want extraneous headings
                mod.getEntryAttributesMap().clear()

                # we want to do our pre-verse content first, but we can't
                # without running it through the optionFilter first.
                # we'll then have to run it through again after, otherwise our
                # entryattributes may go walkabout
                if raw: rawentry_str = rawentry.c_str()
                mod.optionFilter(rawentry, versekey)
                if raw: option_filtered = rawentry.c_str()

                headings = self.get_headings(internal_reference, mod)
                #versekey = VK.castTo(key)
                heading_dicts = []
                raw_headings = []
                for heading, canonical in headings:
                    # the new-style pre-verse content lives wrapped up in
                    # <div>'s - it will contain the <title>, but the div will
                    # be stripped out.
                    # the old-style pre-verse content lives in <title>'s,
                    # which will also be stripped out. Unfortunately, it isn't
                    # that easy to tell whether it did have a title, so we
                    # employ a heuristic - if it starts with an <, it is a new
                    # one...
                    nh = heading.startswith("<")
                    if stripped:
                        heading = mod.StripText(heading).decode(
                            "utf8", "replace")
                    else:
                        heading = render_text(heading).decode(
                            "utf8", "replace")

                    if not nh:
                        cls = " canonical" if (canonical
                                               and canonical == "true") else ""
                        heading = '<h2 class="heading%s">%s</h2>\n' % (cls,
                                                                       heading)

                    if raw:
                        raw_headings.append(heading)
                    heading_dict = dict(heading=heading, canonical=canonical)
                    heading_dict.update(body_dict)
                    heading_dicts.append(heading_dict)

                if stripped:
                    text = mod.StripText(rawentry.c_str(),
                                         rawentry.length()).decode(
                                             "utf-8", "replace")

                else:
                    # we can't use rawentry due to a static local buffer in
                    # swmodule.c; breaks gospel harmonies
                    text = (
                        render_text(  #rawentry.c_str(), rawentry.length()
                        ).decode("utf8", "replace"))

                # get our actual text
                if raw:
                    text = self.process_raw(rawentry_str, text, versekey, mod,
                                            raw_headings, option_filtered)

                user_comments = self.get_user_comments(osisRef, versekey)

                # XXX: This needs to be done better than this.  Move into
                # subclass somehow.
                if isinstance(self, Bible) and display_tags:
                    tags = self.insert_tags(osisRef, versekey,
                                            exclude_topic_tag)
                else:
                    tags = ""

                body_dict.update(
                    dict(text=text, tags=tags, usercomments=user_comments))

                yield body_dict, heading_dicts

                incrementer.increment(1)
                verses_left -= 1

        finally:
            mod.setKey(SW.Key())
            mod.setSkipConsecutiveLinks(old_mod_skiplinks)

        self.end_of_render = ""
        if render_end:
            self.end_of_render = render_end()
コード例 #6
0
ファイル: versecompare.py プロジェクト: nognkantoor/bpbible
    def get_parallel_text(self, ref):
        vk = SW.VerseKey()
        verselist = vk.ParseVerseList(to_str(ref), "", True)

        items = []
        text = ["<table class='parallel_view'>", "<tr>"]
        for item in self.book.GetModules():
            name = item.Name()
            if name in verse_comparison_settings["comparison_modules"]:
                items.append((item,
                              list(
                                  self.book.GetReference_yield(
                                      verselist,
                                      module=item,
                                      max_verses=176,
                                      skip_linked_verses=False))))

                text.append(u"<th>%s</th>" % process_html_for_module(
                    item, u"<b><a href='%s:%s'>"
                    "%s</a></b>" % (BIBLE_VERSION_PROTOCOL, name, name)))

        text.append("</tr>")

        # if we have no bibles to compare, return the empty string
        if not items:
            return ""

        rows = []
        was_clipped = False
        try:
            self.book.templatelist.append(config.parallel_template)
            while True:
                text.append("<tr>")
                for module, refs in items:
                    if not refs:
                        text.append("</tr>")
                        break

                    body_dict, headings = refs.pop(0)

                    if not body_dict:
                        was_clipped = True
                        # remove opening row
                        text.pop()
                        break

                    text_direction = get_module_css_text_direction(module)
                    text.append(
                        u'<td class="parallel_verse" module="%s" dir="%s">' %
                        (module.Name(), text_direction))

                    t = ""
                    for heading_dict in headings:
                        t += biblemgr.bible.templatelist[-1].\
                         headings.safe_substitute(heading_dict)

                    t += biblemgr.bible.templatelist[-1].\
                     body.safe_substitute(body_dict)
                    t = process_html_for_module(module, t)

                    text.append(t)

                    text.append("</td>")

                else:
                    text.append("</tr>")
                    continue

                break
        finally:
            self.book.templatelist.pop()

        text.append("</table>")

        if was_clipped:
            text.append(config.MAX_VERSES_EXCEEDED() % 177)

        return ''.join(text)