Debian Codegraph @

citeproc/frontend.py

raw
1
2 import os
3
4 from warnings import warn
5
6 from lxml import etree
7
8 from . import SCHEMA_PATH, LOCALES_PATH, STYLES_PATH
9 from .model import CitationStylesElement
10 from .formatter import html
11
12
13 class CitationStylesXML(object):
14 def __init__(self, f, validate=True):
15 lookup = etree.ElementNamespaceClassLookup()
16 namespace = lookup.get_namespace('http://purl.org/net/xbiblio/csl')
17 namespace[None] = CitationStylesElement
18 namespace.update(dict([(cls.__name__.replace('_', '-').lower(), cls)
19 for cls in CitationStylesElement.__subclasses__()]))
20
21 self.parser = etree.XMLParser(remove_comments=True, encoding='UTF-8',
22 no_network=True)
23 self.parser.set_element_class_lookup(lookup)
24 self.xml = etree.parse(f, self.parser)#, base_url=".")
25 if validate:
26 self.schema = etree.RelaxNG(etree.parse(SCHEMA_PATH))
27 if not self.schema.validate(self.xml):
28 err = self.schema.error_log
29 #raise Exception("XML file didn't pass schema validation:\n%s" % err)
30 warn("XML file didn't pass schema validation:\n%s" % err)
31 # TODO: proper error reporting
32 self.root = self.xml.getroot()
33
34
35 class CitationStylesLocale(CitationStylesXML):
36 def __init__(self, locale, validate=True):
37 locale_path = os.path.join(LOCALES_PATH, 'locales-{}.xml'.format(locale))
38 try:
39 super(CitationStylesLocale, self).__init__(locale_path,
40 validate=validate)
41 except IOError:
42 raise ValueError("'{}' is not a known locale".format(locale))
43
44
45 class CitationStylesStyle(CitationStylesXML):
46 def __init__(self, style, locale=None, validate=True):
47 style_src = None
48
49 try:
50 # lxml can take file-like objects, so check if we are dealing with
51 # strings first
52 if not isinstance(style, str):
53 pass # pass through for a generic handling below
54 # It could still be a URL etc, first check if style is a path that exists
55 elif os.path.exists(style):
56 style_src = style
57 else:
58 # Try bundled styles
59 bundled_path = os.path.join(STYLES_PATH, f'{style}.csl')
60 if os.path.exists(bundled_path):
61 style_src = bundled_path
62 else:
63 # Try to load from citeproc-py-styles if available
64 try:
65 import citeproc_styles
66 except ImportError:
67 # citeproc-py-styles not installed, raise with helpful message
68 raise ValueError(
69 f"'{style}' not found in bundled styles ({STYLES_PATH}). "
70 f"To access more styles, install the citeproc-py-styles package with: "
71 f"pip install citeproc-py-styles"
72 )
73 try:
74 from citeproc_styles import get_style_filepath
75 style_src = get_style_filepath(style)
76 except (KeyError, FileNotFoundError):
77 # Style not found in citeproc-py-styles
78 raise ValueError(
79 f"'{style}' not found in bundled styles ({bundled_path}) "
80 f"or in citeproc-py-styles package"
81 )
82 except TypeError:
83 pass
84
85 if style_src is None:
86 if style:
87 # Assume it's a file-like object or string containing XML data
88 style_src = style
89 else:
90 # If we couldn't find the style anywhere, raise an error
91 raise ValueError(f"'{style}' is not a known style")
92
93 try:
94 super(CitationStylesStyle, self).__init__(
95 style_src, validate=validate)
96 except IOError:
97 raise ValueError(f"'{style}' is not a known style")
98 if locale is None:
99 locale = self.root.get('default-locale', 'en-US')
100 self.root.set_locale_list(locale, validate=validate)
101
102 def has_bibliography(self):
103 return self.root.bibliography is not None
104
105 def render_citation(self, citation, cites, callback=None):
106 return self.root.citation.render(citation, cites, callback)
107
108 def sort_bibliography(self, citation_items):
109 return self.root.bibliography.sort(citation_items)
110
111 def render_bibliography(self, citation_items):
112 return self.root.bibliography.render(citation_items)
113
114
115 class CitationStylesBibliography(object):
116 def __init__(self, style, source, formatter=html):
117 self.style = style
118 self.source = source
119 self.formatter = self.style.root.formatter = formatter
120 self.keys = []
121 self.items = []
122 self._cites = []
123
124 def register(self, citation, callback=None):
125 citation.bibliography = self
126 for item in citation.cites:
127 if item.key in self.source:
128 if item.key not in self.keys:
129 self.keys.append(item.key)
130 self.items.append(item)
131 elif callback is not None:
132 callback(item)
133
134 def sort(self):
135 self.items = self.style.sort_bibliography(self.items)
136 self.keys = [item.key for item in self.items]
137
138 def cite(self, citation, callback):
139 return self.style.render_citation(citation, self._cites, callback)
140
141 def bibliography(self):
142 return self.style.render_bibliography(self.items)