-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_bbl.py
More file actions
executable file
·185 lines (144 loc) · 4.76 KB
/
Copy pathcreate_bbl.py
File metadata and controls
executable file
·185 lines (144 loc) · 4.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import sys
from typing import Any
from pathlib import Path
from pytex.src.utilities import write_json_file
from pytex.src.utilities import random_string
from pytex.src.utilities import json_to_str
from pytex.src.utilities import ciao
from pytex.src.utilities import text_hash
from pytex.src.utilities import read_json_file
_:Any = write_json_file, random_string, ciao
def line_to_labels(line:str):
"""Return the labels on a citation line."""
start = line.find("{") + 1
end = line.find("}")
content = line[start:end]
return content.split(",")
def is_citation_line(line:str):
"""Say if a line is a citation line."""
return line.startswith("\\citation")
def filter_duplicates(labels:list)->list:
"""
Return a list without the duplicates.
The point of this function is to maintain the order.
"""
new_list = []
for elem in labels:
if elem not in new_list:
new_list.append(elem)
return new_list
def get_labels(aux_file):
"""Return the list of labels in the given aux file."""
try:
lines = aux_file.read_text().splitlines()
except FileNotFoundError:
# first compilation pass the aux file does not exist.
return []
except UnicodeDecodeError as error:
print(error)
print(f"Problem in {aux_file}")
print("delete it and compile again")
sys.exit(1)
cited_labels = []
for line in lines:
if not is_citation_line(line):
continue
line_labels = line_to_labels(line)
for label in line_labels:
# label can be "" when in the LaTeX source we write
# \cite{onelabe,}
if label:
cited_labels.append(label)
cited_labels = filter_duplicates(cited_labels)
return cited_labels
def get_json(json_bib, label)->dict[str,Any]:
"""Return the json of the requested label"""
for elem in json_bib:
if elem["id"] == label:
return elem
raise NameError(f"Pas de {label} dans le bib json.")
def get_bibtex_lines(bibtex_lines, label):
found = False
lines = []
for line in bibtex_lines:
if found:
if line.startswith("@"):
return lines
lines.append(line)
if label not in line:
continue
found = True
if found:
return lines
def bib_hash(elem):
"""Return a hash of the element."""
txt = json_to_str(elem)
return text_hash(txt)
def get_elem_bibitem(elem, num):
"""Return the bibitem line of a bbl entry."""
label = elem["id"]
_ = label
# return f"\\bibitem[{bib_hash(elem)}]{{{label}}}"
return f"\\bibitem[{num}]{{{label}}}"
def get_elem_author(elem):
"""Return the author line."""
if elem.get("author", None) is None:
return None
authors = [f"{author.get('given', '')} {author.get('family', '')}"
for author in elem["author"]]
return " and ".join(authors)+"."
def utf_substitution(text):
"""
Substitute some utf code that LaTeX cannot handle.
example: Levendorskiı̆
"""
answer = text.replace("ı̆", "i")
answer = answer.replace("ı́", "i")
return answer
def extract_url(elem:dict[str,str])->str|None:
"""Return the url in the given bibliography element."""
if 'url' not in elem:
return None
raw_url = elem['url']
url = raw_url
src_dir = Path(__file__).parent / "src"
substitutions:dict[str,str] = read_json_file(src_dir/"percent.json")
for orig, code in substitutions.items():
url = url.replace(orig, code)
return url
def json_to_bbl_elem(elem:dict[str,str], num:int):
"""From a json element, return the bbl code."""
if elem is None:
return ""
list_ans = []
list_ans.append(get_elem_bibitem(elem, num))
list_ans.append(get_elem_author(elem))
title = elem.get("title", None)
date = elem.get("date", None)
url = extract_url(elem)
note = elem.get("note", None)
if title:
list_ans.append(f"\\newblock {title}")
if date:
list_ans.append(f"\\newblock {date}.")
if url:
list_ans.append(f"\\newblock URL \\url{{{url}}}.")
if note:
list_ans.append(f"\\newblock {note}")
lines = [x for x in list_ans if x is not None]
pre_answer = "\n".join(lines)
answer = utf_substitution(pre_answer)
return answer
def get_bbl_code(aux_file, json_bib, bbl_template):
"""Return the code of the bbl file."""
template = bbl_template.read_text()
labels = get_labels(aux_file)
bbl_list = []
num = 0
for label in labels:
num += 1
elem = get_json(json_bib, label)
block = json_to_bbl_elem(elem, num)
bbl_list.append(block)
main_code = "\n\n".join(bbl_list)
return template.replace("**BBL_CODE**", main_code)