Ejemplo n.º 1
0
def render_citation(node, style='apa'):
    """Given a node, return a citation"""
    if isinstance(node, Node):
        data = [
            node.csl,
        ]
    elif isinstance(node, PreprintService):
        csl = preprint_csl(node, node.node)
        data = [
            csl,
        ]
    else:
        raise ValueError

    bib_source = CiteProcJSON(data)

    bib_style = CitationStylesStyle(os.path.join(CITATION_STYLES_PATH, style),
                                    validate=False)

    bibliography = CitationStylesBibliography(bib_style, bib_source,
                                              formatter.plain)

    citation = Citation([CitationItem(node._id)])

    bibliography.register(citation)

    def warn(citation_item):
        pass

    bibliography.cite(citation, warn)
    bib = bibliography.bibliography()
    return unicode(bib[0] if len(bib) else '')
Ejemplo n.º 2
0
def getReferencesFromJupyterNotebook(notebook):
    metadata = notebook.get('metadata')
    references = []
    bibliography = []
    filterReferences = []
    inline_references_table = dict()
    try:
        references = metadata.get('cite2c').get('citations')
        # logger.info("Loging references ---> {0}".format(references))
        bib_source = CiteProcJSON(references.values())
        bib_style = CitationStylesStyle(
            'jdhseo/styles/modern-language-association.csl', validate=False)
        bib = CitationStylesBibliography(bib_style, bib_source, formatter.html)
        # register citation
        for key, entry in bib_source.items():
            # exclude  "undefined" due to bug cite2c
            if key != "undefined":
                bib.register(Citation([CitationItem(key)]))
        for item in bib.bibliography():
            bibliography.append(str(item))
        for k, entry in references.items():
            inline_references_table[k] = getAuthorDateFromReference(entry)
    except Exception as e:
        logger.exception(e)
        pass
    # caseless matching
    #return references, sorted(bibliography, key=str.casefold), inline_references_table
    return references, sorted(bibliography,
                              key=lambda x: re.sub('[^A-Za-z]+', '', x).lower(
                              )), inline_references_table
Ejemplo n.º 3
0
def print_using_citeproc(csl_json, keys, style):

    from citeproc import CitationStylesStyle, CitationStylesBibliography
    from citeproc import Citation, CitationItem
    from citeproc import formatter
    from citeproc.source.json import CiteProcJSON

    def warn(citation_item):
        raise RuntimeError(
            "Reference with key '{}' not found".format(citation_item.key)
        )

    bib_source = CiteProcJSON([csl_json])
    bib_style = CitationStylesStyle(style, validate=False)
    bibliography = CitationStylesBibliography(bib_style, bib_source, formatter.html)
    citations = []
    # the following lines just do whatever example in citeproc repo does
    for key in keys:
        citation = Citation([CitationItem(key)])
        bibliography.register(citation)
        citations.append(citation)
    for citation in citations:
        # unused = bibliography.cite(citation, warn_missing_key)
        unused = bibliography.cite(citation, warn)
    for item in bibliography.bibliography():
        print(str(item))
Ejemplo n.º 4
0
def display_citation(bibtex_metadata, bib_stylename, formatter=formatter.html):
    # valid style names: plos, apa, pnas, nature, bmj, harvard1
    # full list is here: https://github.com/citation-style-language/styles

    bib_style = EnhancedCitationStyle(bib_stylename)
    bibliography = CitationStylesBibliography(bib_style, bibtex_metadata, formatter) #could be formatter.html
    id = "ITEM-1"
    citation = Citation([CitationItem(id)])
    bibliography.register(citation)

    citation_parts = "".join(bibliography.bibliography()[0])
    citation_text = "".join(citation_parts)

    if bib_stylename == 'apa':
        # strip extra periods and spaces that can occur in APA format
        citation_text = citation_text.replace('..', '.')
        citation_text = citation_text.replace('  ', ' ')

        citation_text = citation_text.strip()

        # strip leading comma
        if citation_text.startswith(','):
            citation_text = citation_text.lstrip(',').strip()

        citation_text = strip_duplicate_apa_title(bibtex_metadata, citation_text)

    citation_text = html.unescape(citation_text)

    return citation_text
Ejemplo n.º 5
0
Archivo: bib.py Proyecto: rwblair/BLiMP
def format_bibliography(json_data):
    """ Format CSL-JSON to HTML APA format """
    json_data = _uniqueify(_flatten(json_data))
    bib_source = CiteProcJSON(json_data)
    style_path = get_style_filepath('apa')
    bib_style = CitationStylesStyle(style_path, validate=False)

    # Create the citeproc-py bibliography, passing it the:
    # * CitationStylesStyle,
    # * BibliographySource (CiteProcJSON in this case), and
    # * a formatter (plain, html, or you can write a custom formatter)

    bibliography = CitationStylesBibliography(bib_style, bib_source,
                                              formatter.html)

    # Processing citations in a document needs to be done in two passes as for
    # some CSL styles, a citation can depend on the order of citations in the
    # bibliography and thus on citations following the current one.
    # For this reason, we first need to register all citations with the
    # CitationStylesBibliography.

    for c in json_data:
        bibliography.register(Citation([CitationItem(c['id'])]))

    items = []
    for item in bibliography.bibliography():
        items.append(str(item))

    return items
Ejemplo n.º 6
0
def render_citation(node, style='apa'):
    """Given a node, return a citation"""
    csl = None
    if isinstance(node, PreprintService):
        csl = preprint_csl(node, node.node)
        data = [csl, ]
    else:
        data = [node.csl, ]

    bib_source = CiteProcJSON(data)

    custom = CUSTOM_CITATIONS.get(style, False)
    path = os.path.join(BASE_PATH, 'static', custom) if custom else os.path.join(CITATION_STYLES_PATH, style)
    bib_style = CitationStylesStyle(path, validate=False)

    bibliography = CitationStylesBibliography(bib_style, bib_source, formatter.plain)

    citation = Citation([CitationItem(node._id)])

    bibliography.register(citation)

    bib = bibliography.bibliography()
    cit = unicode(bib[0] if len(bib) else '')

    title = csl['title'] if csl else node.csl['title']
    if cit.count(title) == 1:
        i = cit.index(title)
        prefix = clean_up_common_errors(cit[0:i])
        suffix = clean_up_common_errors(cit[i + len(title):])
        cit = prefix + title + suffix
    elif cit.count(title) == 0:
        cit = clean_up_common_errors(cit)

    return cit
Ejemplo n.º 7
0
def apa_html_utf8(json_data, alocale='en-US'):
    # CiteProcJSON receives a [{}] not a {}
    bib_source = CiteProcJSON([json_data])
    apa = CitationStylesStyle('apa', locale=alocale, validate=False)
    bibliography = CitationStylesBibliography(apa, bib_source, formatter.html)
    citation = Citation([CitationItem(json_data['id'])])
    bibliography.register(citation)

    # handle python weird string type
    return str(''.join(bibliography.bibliography()[0]).encode('utf-8'))
Ejemplo n.º 8
0
 def cite(self):
     style_path = get_style_filepath(CSL_STYLE)
     print(style_path)
     bib_style = CitationStylesStyle(style_path, validate=False)
     bibliography = CitationStylesBibliography(bib_style,
                                               CiteProcJSON([self.fields]),
                                               formatter.html)
     citation = Citation([CitationItem(self.instance.slug)])
     bibliography.register(citation)
     return str(bibliography.bibliography()[0])
Ejemplo n.º 9
0
def make_citation_by_string(publications):
    bib_str = render_to_string('semsite/export/publications.bib',
                               {'publications': publications})
    bib = bibtex.BibTeX(io.StringIO(bib_str), encoding='utf-8')
    bib_style = CitationStylesStyle('gost-r-7-0-5-2008',
                                    'ru-ru',
                                    validate=False)
    bibliography = CitationStylesBibliography(bib_style, bib)
    citation_items = [CitationItem(key) for key in bib]
    citation = Citation(citation_items)
    bibliography.register(citation)
    return bibliography.cite(citation, warn)
Ejemplo n.º 10
0
    def __init__(self,
                 for_cls,
                 csl_style,
                 export_format=adsFormatter.unicode,
                 journal_format=adsJournalFormat.default):
        """

        :param for_cls: input data for this class
        :param csl_style: export journal style
        :param export_format: export format
        """
        self.for_cls = for_cls
        self.csl_style = csl_style
        self.export_format = export_format
        self.journal_format = journal_format
        self.citation_item = []
        self.bibcode_list = []

        self.__update_title()

        # Process the JSON data to generate a citaproc-py BibliographySource.
        bib_source = CiteProcJSON(self.for_cls)

        csl_style_fullpath = os.path.realpath(__file__ + "/../../cslstyles")

        # load a CSL style (from the current directory)
        bib_style = CitationStylesStyle(os.path.join(csl_style_fullpath + '/' +
                                                     csl_style),
                                        validate=False)

        # Create the citaproc-py bibliography, passing it the:
        # * CitationStylesStyle,
        # * BibliographySource (CiteProcJSON in this case), and
        # * a formatter (plain, html, or you can write a custom formatter)
        # we are going to have CSL format everything using html and then format it as we need to match the
        # classic output
        self.bibliography = CitationStylesBibliography(bib_style, bib_source,
                                                       formatter.html)

        # Processing citations in a document needs to be done in two passes as for some
        # CSL styles, a citation can depend on the order of citations in the
        # bibliography and thus on citations following the current one.
        # For this reason, we first need to register all citations with the
        # CitationStylesBibliography.

        for item in self.for_cls:
            citation = Citation([CitationItem(item['id'])])
            self.citation_item.append(citation)
            self.bibliography.register(citation)
            # this is actually a bibcode that was passed in, but we have to use
            # one of CSLs predefined ids
            self.bibcode_list.append(''.join(item.get('locator', '')))
Ejemplo n.º 11
0
def generate_md(db, min_year=float('-inf'), max_year=float('inf'), group_by_year=True):

    directory = os.path.dirname(os.path.abspath(__file__))
    file_location = directory + os.path.sep + "static" + os.path.sep + "SasView_linktitle"
    bib_style = CitationStylesStyle(file_location, validate=False)

    # Create the citeproc-py bibliography, passing it the:
    # * CitationStylesStyle,
    # * BibliographySource (CiteProcJSON in this case), and
    # * a formatter (plain, html, or you can write a custom formatter)
    
    # add id to each item:
    items = db.items()
    for k, v in items:
        v['id'] = k
    
    bib_source = CiteProcJSON([v for k,v in items])
    year_lookup = sort_year(items)
    years = list(year_lookup.keys())
    years.sort()
    output_years = [year for year in years if year <= max_year and year >=min_year]
    year_cite_items = []
    year_link_items = []
    patent_items = []
    for year in output_years:
        year_link_items.append('[{0}](#{0})'.format(year))
        keys = year_lookup[year]
        keys.sort(key=lambda l: get_date_string(db[l]), reverse=True)
        bibliography = CitationStylesBibliography(bib_style, bib_source, formatter.plain)
        citations = [Citation([CitationItem(k)]) for k in keys]
        for c in citations:
            bibliography.register(c)
        
        bib = bibliography.bibliography()
        cite_bib = []
        for k, b in zip(keys, bib):
            if db[k].get('type', None) == 'patent':
                patent_items.append(unescape("".join(b)))
            else:
                cite_bib.append(b)
        bib_output = [unescape("".join(b)) for b in cite_bib]
        year_output = ['## {0}\n'.format(year)]
        year_output.append('<small>[top](#acknowledgements-and-contacts)</small>\n')
        year_output.append('---\n')
        for i, bib_i in enumerate(bib_output):
            bib_final = ("{0}. " + bib_i).format(i)
            year_output.append(bib_final)
        year_cite_items.append("\n".join(year_output))
    return {"citations": year_cite_items, "links": year_link_items, "patents": patent_items}
Ejemplo n.º 12
0
    def serialize(self, pid, record, links_factory=None, **kwargs):
        """Serialize a single record.

        :param pid: Persistent identifier instance.
        :param record: Record instance.
        :param links_factory: Factory function for record links.
        """
        data = self.serializer.serialize(pid, record, links_factory)
        source = self._get_source(data)
        style = CitationStylesStyle(validate=False, **self._get_args(**kwargs))
        bib = CitationStylesBibliography(style, source, formatter.plain)
        citation = Citation([CitationItem(pid.pid_value)])
        bib.register(citation)

        return self._clean_result(''.join(bib.bibliography()[0]))
Ejemplo n.º 13
0
def bibToCite(bibfile, ID):
    bib_source = BibTeX(bibfile)

    style_path = get_style_filepath('modern-language-association')
    bib_style = CitationStylesStyle(style_path, validate=False)

    bibliography = CitationStylesBibliography(bib_style, bib_source,
                                              formatter.plain)

    citation1 = Citation([CitationItem(ID)])

    bibliography.register(citation1)

    with open('out.txt', 'w') as f:
        for item in bibliography.bibliography():
            print(str(item), file=f)
Ejemplo n.º 14
0
def get_citation_string(json, id, style, locale):
    """Get the citation string from CiteProc library."""
    def _clean_result(text):
        """Remove double spaces, punctuation."""
        text = re.sub(r"\s\s+", " ", text)
        text = re.sub(r"\.\.+", ".", text)
        return text

    source = CiteProcJSON([json])
    citation_style = CitationStylesStyle(validate=False,
                                         style=style,
                                         locale=locale)
    bib = CitationStylesBibliography(citation_style, source, formatter.plain)
    citation = Citation([CitationItem(id)])
    bib.register(citation)

    return _clean_result(str(bib.bibliography()[0]))
Ejemplo n.º 15
0
def display_citation(bibtex_metadata, bib_stylename, formatter=formatter.html):
    # valid style names: plos, apa, pnas, nature, bmj, harvard1
    # full list is here: https://github.com/citation-style-language/styles

    bib_style = EnhancedCitationStyle(bib_stylename)
    bibliography = CitationStylesBibliography(
        bib_style, bibtex_metadata, formatter)  #could be formatter.html
    id = "ITEM-1"
    citation = Citation([CitationItem(id)])
    bibliography.register(citation)

    citation_parts = u"".join(bibliography.bibliography()[0])
    citation_text = u"".join(citation_parts)

    html_parser = HTMLParser()
    citation_text = html_parser.unescape(citation_text)

    return citation_text
Ejemplo n.º 16
0
    def ama_html(self):
        if not self.citeproc_json:
            return ""

        bibliography = CitationStylesBibliography(
            CitationStylesStyle(
                str(
                    Path(__file__).parent / "styles" /
                    "american-medical-association-no-url.csl")),
            self.bib_source,
            formatter.html,
        )
        bibliography.register(Citation([CitationItem(self.doi)]))

        # The bibliography only contains 1 element
        citation = str(bibliography.bibliography()[0])
        citation = re.sub(r"^1\. ", "", citation)

        return clean(citation)
Ejemplo n.º 17
0
def render_citation(node, style='apa'):
    """Given a node, return a citation"""
    if isinstance(node, Node):
        data = [node.csl, ]
    elif isinstance(node, PreprintService):
        csl = preprint_csl(node, node.node)
        data = [csl, ]
    else:
        raise ValueError

    bib_source = CiteProcJSON(data)

    bib_style = CitationStylesStyle(os.path.join(CITATION_STYLES_PATH, style), validate=False)

    bibliography = CitationStylesBibliography(bib_style, bib_source, formatter.plain)

    citation = Citation([CitationItem(node._id)])

    bibliography.register(citation)

    def warn(citation_item):
        pass

    bibliography.cite(citation, warn)
    bib = bibliography.bibliography()

    if len(bib):
        doi = data[0].get('DOI')
        if style == 'apa':
            first_segment = [list(bib[0])[0][:-2]]
            return ''.join(first_segment + list(bib[0])[1:13]) if doi else ''.join(first_segment + list(bib[0])[1:12] + list(bib[0])[13:])
        elif style == 'modern-language-association':
            return ''.join(list(bib[0])[:4] + ['.'] + list(bib[0])[4:5] + list(bib[0])[6:-2])
        elif style == 'chicago-author-date':
            return ''.join(list(bib[0])[0:3] + ['.'] + list(bib[0])[3:4] + [' '] + list(bib[0])[5:])
        else:
            return unicode(bib[0])
    else:
        return ''
Ejemplo n.º 18
0
def citeproc_csl(csl_json: Dict[str, Any],
                 style: str,
                 html: bool = False) -> str:
    """
    Renders a release entity to a styled citation.

    Notable styles include:
    - 'csl-json': special case to JSON encode the structured CSL object (via
      release_to_csl())
    - bibtext: multi-line bibtext format (used with LaTeX)

    Returns a string; if the html flag is set, and the style isn't 'csl-json'
    or 'bibtex', it will be HTML. Otherwise plain text.
    """
    if not csl_json.get("id"):
        csl_json["id"] = "unknown"
    if style == "csl-json":
        return json.dumps(csl_json)
    bib_src = CiteProcJSON([csl_json])
    form = formatter.plain
    if html:
        form = formatter.html
    style_path = get_style_filepath(style)
    bib_style = CitationStylesStyle(style_path, validate=False)
    bib = CitationStylesBibliography(bib_style, bib_src, form)
    bib.register(Citation([CitationItem(csl_json["id"])]))
    lines = bib.bibliography()[0]
    if style == "bibtex":
        out = ""
        for line in lines:
            if line.startswith(" @"):
                out += "@"
            elif line.startswith(" "):
                out += "\n " + line
            else:
                out += line
        return "".join(out)
    else:
        return "".join(lines)
Ejemplo n.º 19
0
def get_bib():
    bib_source = BibTeX('notebooks/bibliography.bib', encoding='utf8')
    bib_style = CitationStylesStyle('notebooks/springer.csl', validate=False)

    bibliography = CitationStylesBibliography(bib_style, bib_source,
                                              formatter.html)
    bib_cites = [Citation([CitationItem(item)]) for item in bib_source]

    for item in bib_cites:
        bibliography.register(item)
    for item in bib_cites:
        bibliography.cite(item, _cite_warn)

    num = len(bibliography.keys)
    bib_entries = dict()
    for i in range(num):
        bib = ''.join(bibliography.bibliography()[i])
        # remove beginning digits and \. from bib entries
        bib = '{}.&emsp;' + re.sub("^\d+\.", "", bib)
        bib_entries[bibliography.keys[i]] = bib

    return bib_entries
Ejemplo n.º 20
0
def run_citeproc_releases(args):
    for line in args.json_input:
        line = line.strip()
        if not line:
            continue
        entity = entity_from_json(line, ReleaseEntity, api_client=args.api.api_client)
        csl_json = release_to_csl(entity)
        # XXX:
        csl_json['id'] = "release:" + (entity.ident or "unknown")
        if args.style == "csl-json":
            args.json_output.write(json.dumps(csl_json) + "\n")
            continue
        bib_src = CiteProcJSON([csl_json])
        form = formatter.plain
        if args.html:
            form = formatter.html
        style_path = get_style_filepath(args.style)
        bib_style = CitationStylesStyle(style_path, validate=False)
        bib = CitationStylesBibliography(bib_style, bib_src, form)
        bib.register(Citation([CitationItem(csl_json['id'])]))
        # XXX:
        #args.json_output.write(
        #    json.dumps(release_to_csl(entity)) + '\n')
        lines = bib.bibliography()[0]
        if args.style == "bibtex":
            for l in lines:
                if l.startswith(" @"):
                    args.json_output.write("\n@")
                elif l.startswith(" "):
                    #print("line: START|{}|END".format(l))
                    args.json_output.write("\n  " + l)
                else:
                    args.json_output.write(l)
        else:
            args.json_output.write(''.join(lines) + "\n")
        print()
Ejemplo n.º 21
0
def render_citation(node, style='apa'):
    """Given a node, return a citation"""
    data = [
        node.csl,
    ]

    bib_source = CiteProcJSON(data)

    bib_style = CitationStylesStyle(os.path.join(CITATION_STYLES_PATH, style),
                                    validate=False)

    bibliography = CitationStylesBibliography(bib_style, bib_source,
                                              formatter.plain)

    citation = Citation([CitationItem(node._id)])

    bibliography.register(citation)

    def warn(citation_item):
        pass

    bibliography.cite(citation, warn)
    bib = bibliography.bibliography()
    return unicode(bib[0] if len(bib) else '')
Ejemplo n.º 22
0
# load a CSL style
fCSL = open('static/csl/mla-isawbib-full.csl', "rb")
fCSL = open('static/csl/mla-isawbib-authorless.csl', "rb")
bib_style = CitationStylesStyle(fCSL, validate=False)

# Create the citeproc-py bibliography, passing it the:
# * CitationStylesStyle,
# * BibliographySource (CiteProcJSON in this case), and
# * a formatter (plain, html, or you can write a custom formatter)

bibliography = CitationStylesBibliography(bib_style, bib_source,
                                          formatter.html)

# Processing citations in a document needs to be done in two passes as for some
# CSL styles, a citation can depend on the order of citations in the
# bibliography and thus on citations following the current one.
# For this reason, we first need to register all citations with the
# CitationStylesBibliography.
for item in bibTeX.entries:
    print(item['ID'])
    citation = Citation([CitationItem(item['ID'])])
    bibliography.register(citation)

print('')
print('Bibliography')
print('------------')

for item in bibliography.bibliography():
    print(str(item))
Ejemplo n.º 23
0
def render_citation(node, style='apa'):
    """Given a node, return a citation"""
    reformat_styles = [
        'apa', 'chicago-author-date', 'modern-language-association'
    ]
    csl = None
    if isinstance(node, PreprintService):
        csl = preprint_csl(node, node.node)
        data = [
            csl,
        ]
    else:
        data = [
            node.csl,
        ]

    bib_source = CiteProcJSON(data)

    custom = CUSTOM_CITATIONS.get(style, False)
    path = os.path.join(BASE_PATH, 'static',
                        custom) if custom else os.path.join(
                            CITATION_STYLES_PATH, style)

    try:
        bib_style = CitationStylesStyle(path, validate=False)
    except ValueError:
        citation_style = CitationStyle.load(style)
        if citation_style is not None and citation_style.has_parent_style:
            parent_style = citation_style.parent_style
            parent_path = os.path.join(CITATION_STYLES_PATH, parent_style)
            bib_style = CitationStylesStyle(parent_path, validate=False)
        else:
            raise ValueError(
                'Unable to find a dependent or independent parent style related to {}.csl'
                .format(style))

    bibliography = CitationStylesBibliography(bib_style, bib_source,
                                              formatter.plain)

    citation = Citation([CitationItem(node._id)])

    bibliography.register(citation)

    bib = bibliography.bibliography()
    cit = unicode(bib[0] if len(bib) else '')

    title = csl['title'] if csl else node.csl['title']
    title = title.rstrip('.')
    if cit.count(title) == 1:
        i = cit.index(title)
        prefix = clean_up_common_errors(cit[0:i])
        suffix = clean_up_common_errors(cit[i + len(title):])
        if (style in reformat_styles):
            if suffix[0:1] == '.':
                suffix = suffix[1:]
            if title[-1] != '.':
                title += '.'
        cit = prefix + title + suffix
    elif cit.count(title) == 0:
        cit = clean_up_common_errors(cit)
        if (style in reformat_styles):
            cit = add_period_to_title(cit)

    if isinstance(node, PreprintService):
        cit_node = node.node
    else:
        cit_node = node

    if style == 'apa':
        cit = apa_reformat(cit_node, cit)
    if style == 'chicago-author-date':
        cit = chicago_reformat(cit_node, cit)
    if style == 'modern-language-association':
        cit = mla_reformat(cit_node, cit)

    return cit
Ejemplo n.º 24
0
# Create the citeproc-py bibliography, passing it the:
# * CitationStylesStyle,
# * BibliographySource (BibTeX in this case), and
# * a formatter (plain, html, or you can write a custom formatter)

bibliography = CitationStylesBibliography(bib_style, bib_source,
                                          formatter.plain)


# Processing citations in a document needs to be done in two passes as for some
# CSL styles, a citation can depend on the order of citations in the
# bibliography and thus on citations following the current one.
# For this reason, we first need to register all citations with the
# CitationStylesBibliography.

citation1 = Citation([CitationItem('whole-collection')])
citation2 = Citation([CitationItem('whole-set'), CitationItem('misc-full')])
citation3 = Citation([CitationItem('techreport-full')])
citation4 = Citation([CitationItem('mastersthesis-minimal')])
citation5 = Citation([CitationItem('inproceedings-full'),
                      CitationItem('unpublished-full')])

bibliography.register(citation1)
bibliography.register(citation2)
bibliography.register(citation3)
bibliography.register(citation4)
bibliography.register(citation5)


# In the second pass, CitationStylesBibliography can generate citations.
# CitationStylesBibliography.cite() requires a callback function to be passed
Ejemplo n.º 25
0
 def parse(self, document):
     keys = map(lambda x: x.strip(), self.get('id').split(','))
     items = [CitationItem(key) for key in keys]
     citation = Citation(items)
     document.bibliography.register(citation)
     return CitationField(citation)
Ejemplo n.º 26
0
# Create the citeproc-py bibliography, passing it the:
# * CitationStylesStyle,
# * BibliographySource (CiteProcJSON in this case), and
# * a formatter (plain, html, or you can write a custom formatter)

bibliography = CitationStylesBibliography(bib_style, bib_source,
                                          formatter.plain)

# Processing citations in a document need to be done in two passes as for some
# CSL styles, a citation can depend on the order of citations in the
# bibliography and thus on citations following the current one.
# For this reason, we first need to register all citations with the
# CitationStylesBibliography.

citation1 = Citation([CitationItem('ITEM-3')])
citation2 = Citation([CitationItem('ITEM-1'), CitationItem('ITEM-2')])
citation3 = Citation([CitationItem('ITEM-4')])
citation4 = Citation([CitationItem('ITEM-5')])
citation5 = Citation([CitationItem('MISSING')])

bibliography.register(citation1)
bibliography.register(citation2)
bibliography.register(citation3)
bibliography.register(citation4)
bibliography.register(citation5)

# In the second pass, CitationStylesBibliography can generate citations.
# CitationStylesBibliography.cite() requires a callback function to be passed
# along to be called in case a CitationItem's key is not present in the
# bilbiography.
Ejemplo n.º 27
0
# Create the citeproc-py bibliography, passing it the:
# * CitationStylesStyle,
# * BibliographySource (BibTeX in this case), and
# * a formatter (plain, html, or you can write a custom formatter)

bibliography = CitationStylesBibliography(bib_style, bib_source,
                                          formatter.plain)

# Processing citations in a document need to be done in two passes as for some
# CSL styles, a citation can depend on the order of citations in the
# bibliography and thus on citations following the current one.
# For this reason, we first need to register all citations with the
# CitationStylesBibliography.

citation1 = Citation([CitationItem('whole-collection')])
citation2 = Citation([CitationItem('whole-set'), CitationItem('misc-full')])
citation3 = Citation([CitationItem('techreport-minimal')])

bibliography.register(citation1)
bibliography.register(citation2)
bibliography.register(citation3)

# In the second pass, CitationStylesBibliography can generate citations.
# CitationStylesBibliography.cite() requires a callback function to be passed
# along to be called in case a CitationItem's key is not present in the
# bilbiography.


def warn(citation_item):
    print("WARNING: Reference with key '{}' not found in the bibliography.".
Ejemplo n.º 28
0
            f.write(unicode(str(i)) + '. ')
            i = i + 1
        f.write(unicode(str(item)) + '\n')
    f.close()


def write_to_bbl(filename, bibliography):
    f = open(filename, 'w', encoding='utf8')
    f.write('\\begin{thebibliography}{}\n')
    i = 0
    for item in bibliography.bibliography():
        f.write('\\bibitem{' + my_cities[i] + '}')
        f.write(unicode(str(item)) + '\n')
        i = i + 1
    f.write('\\end{thebibliography}')
    f.close()


bib_source = BibTeX('literature.bib', encoding='utf8')
bib_style = CitationStylesStyle('gost-r-7-0-5-2008',
                                locale='ru-RU',
                                validate=False)
bibliography = CitationStylesBibliography(bib_style, bib_source,
                                          formatter.plain)

get_cities('literature.bib')
for i in range(len(my_cities)):
    bibliography.register(Citation([CitationItem(my_cities[i])]))

write_to_txt('my_bibliography.txt', bibliography)
write_to_bbl('my_bibliography.bbl', bibliography)
Ejemplo n.º 29
0
 def prepareCitations(self):
     """
     """
     for cit in self.doc.citations:
         self.citations[cit["id"]] = Citation([CitationItem(cit["ref_id"])])
         self.bibliography.register(self.citations[cit["id"]])
Ejemplo n.º 30
0
def render_bibliography(docs=None, format='html', locale='', style='', commit_link=False, commit_system=''):

    if docs is None:
        docs = []

    publist = ''
    # logging.debug('csl-docs: %s' % docs)
    if len(docs) > 0:

        locales_url = secrets.CITEPROC_LOCALES_FILE

        with open(locales_url) as data_file:
            locales = json.load(data_file)

        bib_source = CiteProcJSON(docs)
        # load a CSL style (from the current directory)
        locale = '%s/csl-locales/locales-%s' % (secrets.CSL_DATA_DIR, locales.get('primary-dialects').get(locale))
        # logging.info('locale: %s' % locale)
        bib_style = CitationStylesStyle('%s/csl/%s' % (secrets.CSL_DATA_DIR, style),
                                        locale=locale,
                                        validate=False)
        # Create the citeproc-py bibliography, passing it the:
        # * CitationStylesStyle,
        # * BibliographySource (CiteProcJSON in this case), and
        # * a formatter (plain, html, or you can write a custom formatter)
        bibliography = CitationStylesBibliography(bib_style, bib_source, formatter.html)
        # get a list of the item ids and register them to the bibliography object

        def warn(citation_item):
            logging.warning(
                "WARNING: Reference with key '{}' not found in the bibliography.".format(citation_item.key)
            )

        for item in docs:
            citation = Citation([CitationItem(item.get('id'))])
            bibliography.register(citation)
            bibliography.cite(citation, warn)

        # And finally, the bibliography can be rendered.
        if format == 'html':
            publist += '<div class="csl-bib-body">'

        idx = 0
        for item in bibliography.bibliography():
            # TODO Formatierung
            # logging.info('CSL item: %s' % item)
            # logging.info('CSL item ID: %s' % docs[idx].get('id'))
            if format == 'html':
                publist += '<div class="csl-entry">'
                if commit_link:
                    publist += '<span class="glyphicon glyphicon-minus" aria-hidden="true"></span> '

            if format == 'html':
                urls = re.findall(urlmarker.URL_REGEX, str(item))
                # logging.info(urls)

                for url in urls:
                    item = item.replace(url, '<a href="%s">%s</a>' % (url, url))

            publist += str(item)

            if commit_link and commit_system:
                if commit_system == 'crossref':
                    publist += ' <span class="glyphicon glyphicon-transfer" aria-hidden="true"></span> <a href="%s?doi=%s">%s</a>' % (url_for("new_by_identifiers"), docs[idx].get('id'), lazy_gettext('Use this Record'))
                else:
                    publist += ' <span class="glyphicon glyphicon-transfer" aria-hidden="true"></span> <a href="%s?source=%s&id=%s">%s</a>' % (url_for("new_by_identifiers"), commit_system, docs[idx].get('id'), lazy_gettext('Use this Record'))

            if format == 'html':
                publist += '</div>'

            idx += 1

        if format == 'html':
            publist += '</div>'

    return publist