-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkBib.py
195 lines (167 loc) · 7.04 KB
/
checkBib.py
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
186
187
188
189
190
191
192
193
194
195
import bibtexparser, sys, re, codecs, unicodedata, argparse
from bibtexparser.customization import homogenize_latex_encoding
warning = 0
def check_if_string_in_file(file_name, string_to_search):
with open(file_name, 'r') as read_obj:
i = 0
for line in read_obj:
i += 1
if string_to_search in line:
return i
return 0
def erroID(i, ID, default):
print("\n---------------/\\---------------")
print("Padrão incorreto no campo ID da referencia:", i, "(", ID,
");\nVerifique o(s) nome(s) do(s) autor(es), um possível padrão é:")
print(default)
print("---------------\\/---------------")
def erroAno(i, ID, default):
print("\n---------------/\\---------------")
print("Padrão incorreto no campo ID da referencia:", i, "(", ID,
");\nVerifique ano da publicação, um possível padrão é:")
print(default)
print("---------------\\/---------------")
def callWarn(i, ID, default):
global warning
warning += 1
ano = re.findall(r'\d+', ID)
if ano == [] or str(ano[0]) not in default:
erroAno(i, ID, default)
else:
erroID(i, ID, default)
def with1author(authors, default, i, ID):
author = authors[0].split(',')
if(len(author) == 1):
author = authors[0].split(' ')
default = author[-1]+year
if not ID.startswith(default):
callWarn(i, ID, default)
return 0
else:
author = author[0].split(' ')
default = author[-1]+year
if len(author) > 1:
if author[0]+author[1] in ID:
return default
if not ID.startswith(default):
callWarn(i, ID, default)
return 0
return default
def with2authors(authors, default, i, ID):
author1 = authors[0].split(',')
author2 = authors[1].split(',')
if(len(author1) == 1 and len(author2) == 1):
if len(author1) > 1:
authors[0] = author1[0]
if len(author2) > 1:
authors[1] = author2[0]
author1 = authors[0].split(' ')
author2 = authors[1].split(' ')
default = author1[-1]+'&'+author2[-1]+year
if not ID.startswith(default):
callWarn(i, ID, default)
return 0
else:
author1 = author1[0].split(' ')
author2 = author2[0].split(' ')
default = author1[-1]+'&'+author2[-1]+year
if len(author1) > 1:
if author1[0]+author1[1] in ID:
return default
if len(author2) > 1:
if author2[0]+author2[1] in ID:
return default
if not ID.startswith(default):
callWarn(i, ID, default)
return 0
return default
def withmanyauthors(authors, default, i, ID):
author = authors[0].split(',')
if(len(author) == 1):
author = authors[0].split(' ')
default = author[-1]+'+'+year
if not ID.startswith(default):
callWarn(i, ID, default)
return 0
else:
author = author[0].split(' ')
default = author[-1]+'+'+year
if len(author) > 1:
if author[0]+author[1] in ID:
return default
if not ID.startswith(default):
callWarn(i, ID, default)
return 0
return default
try:
parser = argparse.ArgumentParser(description='Check the entries of bibtex files are in accordance with the estabilished standard available at https://wiki.inf.ufrgs.br/Maslab_FAQ#BibTeX')
parser.add_argument('-f', dest='file',
help='File .bib to be checked')
parser.add_argument('-w', dest='warnings', type=int, default=1,
help='Show all warnings messages. 0 = False (only warnings) or 1 = True (all messages).\nDefault is 1 = True')
args = parser.parse_args()
f = codecs.open(args.file, encoding='utf-8', errors='strict')
i = 1
for line in f:
i += 1
pass
with open(args.file) as bibtex_file:
bib_database = bibtexparser.bparser.BibTexParser(common_strings=True, ignore_nonstandard_types=False, interpolate_strings=False).parse_file(bibtex_file)
except UnicodeDecodeError as e:
print("invalid utf-8 next to the line", str(i+1))
print(e)
exit()
try:
for i in range(0, len(bib_database.entries)):
ID = bib_database.entries[i]['ID']
default = ''
unCheck = ['booklet', 'manual', 'proceedings', 'misc']
if bib_database.entries[i]['ENTRYTYPE'] not in unCheck:
if 'author' not in bib_database.entries[i]:
checks = bib_database.entries[i]['editor']
else:
checks = bib_database.entries[i]['author']
if '\"' in checks:
if args.warnings:
print("\n---------------/\\---------------")
print("---------------Uncheckable", ID, ", umlaut encontrado, realize uma checagem manual---------------")
print("---------------\\/---------------")
continue
title = bib_database.entries[i]['title']
if '{' in title and '}' in title and args.warnings:
print("\n---------------", ID, ", contem chaves duplas ou em excesso no titulo, linha:", check_if_string_in_file(args.file, title) , ", verifique a necessassidade delas---------------")
print("Titulo:", title, end="\n\n")
for rep in ['\\v', '\\c ', '\\c', '\\`', '\\', '\'', '{', '}', '~', '^']:
checks = checks.replace(rep, '')
checks = checks.replace('\n', ' ')
if '-' in checks and '-' not in ID:
checks = checks.replace('-', '')
checks = unicodedata.normalize('NFD', checks).encode('ascii', 'ignore').decode("utf-8")
authors = checks.split(' and ')
year = str(int(bib_database.entries[i]['year']))
if len(authors) == 1:
if ("et al" in authors[0]):
default = withmanyauthors(authors, default, i, ID)
if (default == 0):
continue
else:
default = with1author(authors, default, i, ID)
if (default == 0):
continue
elif len(authors) == 2:
default = with2authors(authors, default, i, ID)
if (default == 0):
continue
elif len(authors) > 2:
default = withmanyauthors(authors, default, i, ID)
if (default == 0):
continue
elif args.warnings:
print("\n---------------/\\---------------")
print("---------------Uncheckable", ID, ", tipo de entrada pode não ser padronizada, realize uma checagem manual---------------")
print("---------------\\/---------------")
except Exception as e:
print(e ,"faltando no ID:", ID)
exit()
print("Total de warnings: ", warning, "*")
print("* Nem todos os warnings são necessariamente erros, ainda não encontramos uma boa forma de verificar nomes separados por - e nomes com de, da, do...")