| 1 |
#!/usr/bin/env python3 |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
# ========================================================================== |
| 4 |
# ____ _ _ _____ __ ______ |
| 5 |
# | __ )(_) |_|_ _|__\ \/ / ___|___ _ ____ __ |
| 6 |
# | _ \| | '_ \| |/ _ \ / | / _ \| '_ \ \ / / |
| 7 |
# | |_) | | |_) | | __// \ |__| (_) | | | \ V / |
| 8 |
# |____/|_|_.__/|_|\___/_/\_\____\___/|_| |_|\_/ |
| 9 |
# |
| 10 |
# --- BibTeX Converter --- |
| 11 |
# https://www.nntb.no/~dreibh/bibtexconv/ |
| 12 |
# ========================================================================== |
| 13 |
# |
| 14 |
# IETF2BibTeX |
| 15 |
# Copyright (C) 2014-2026 by Thomas Dreibholz |
| 16 |
# |
| 17 |
# This program is free software: you can redistribute it and/or modify |
| 18 |
# it under the terms of the GNU General Public License as published by |
| 19 |
# the Free Software Foundation, either version 3 of the License, or |
| 20 |
# (at your option) any later version. |
| 21 |
|
| 22 |
# This program is distributed in the hope that it will be useful, |
| 23 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 24 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 25 |
# GNU General Public License for more details. |
| 26 |
# |
| 27 |
# You should have received a copy of the GNU General Public License |
| 28 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 29 |
# |
| 30 |
# Contact: [email protected] |
| 31 |
|
| 32 |
import codecs |
| 33 |
import csv |
| 34 |
import hashlib |
| 35 |
import os |
| 36 |
import re |
| 37 |
import sys |
| 38 |
import urllib.request |
| 39 |
import xml.dom.minidom |
| 40 |
|
| 41 |
if sys.version_info < (3, 9): |
| 42 |
sys.stderr.write('ERROR: ' + sys.argv[0] + ' requires Python 3.9 or later!\n') |
| 43 |
sys.exit(1) |
| 44 |
|
| 45 |
from typing import Final, BinaryIO, TextIO, Sequence |
| 46 |
|
| 47 |
|
| 48 |
datatrackerPrefix : Final[str] = 'https://datatracker.ietf.org/doc/' |
| 49 |
draftPrefix : Final[str] = 'https://bib.ietf.org/public/rfc/bibxml3/reference.I-D.' |
| 50 |
rfcPrefix : Final[str] = 'https://bib.ietf.org/public/rfc/bibxml/reference.RFC.' |
| 51 |
verboseMode : bool = True |
| 52 |
authorsFixFile : str | None = 'DEFAULT' |
| 53 |
|
| 54 |
|
| 55 |
# Documents where meta-information XML is wrong: |
| 56 |
blacklistTable = [ |
| 57 |
'draft-ahmed-lssctp', |
| 58 |
'draft-adams-qos-broadband', |
| 59 |
'draft-lopez-mptcp-middlebox', |
| 60 |
'draft-wei-mptcp-proxy-mechanism', |
| 61 |
'draft-ietf-rserpool-api', |
| 62 |
'draft-ietf-rserpool-applic', |
| 63 |
'draft-ietf-rserpool-arch', |
| 64 |
'draft-ietf-rserpool-comp', |
| 65 |
'draft-ietf-rserpool-mib', |
| 66 |
'draft-ietf-rserpool-tcpmapping', |
| 67 |
'draft-iyengar-sctp-cacc', |
| 68 |
'draft-xue-mptcp-tmpp-unware-hosts' |
| 69 |
] |
| 70 |
|
| 71 |
monthIDTable = [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', |
| 72 |
'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ] |
| 73 |
monthNameTable = [ 'January', 'February', 'March', 'April', |
| 74 |
'May', 'June', 'July', 'August', |
| 75 |
'September', 'October', 'November', 'December', |
| 76 |
'INVALID' ] |
| 77 |
|
| 78 |
|
| 79 |
# ###### Fetch URL, with caching ############################################ |
| 80 |
def fetch(url : str) -> BinaryIO: |
| 81 |
urlHash : Final[str] = hashlib.sha256(url.encode('utf-8')).hexdigest() |
| 82 |
cacheFileName : Final[str] = '/tmp/ietf2bibtex-' + urlHash + '.data' |
| 83 |
|
| 84 |
if not os.path.exists(cacheFileName): |
| 85 |
if verboseMode == True: |
| 86 |
sys.stderr.write('Fetching ' + url + ' into ' + cacheFileName + ' ...\n') |
| 87 |
|
| 88 |
# www.rfc-editor.org requires a user-agent: |
| 89 |
opener : urllib.request.OpenerDirector = urllib.request.build_opener() |
| 90 |
opener.addheaders = [ ( 'User-agent', 'bibtexconv/2.0' ) ] |
| 91 |
urllib.request.install_opener(opener) |
| 92 |
|
| 93 |
inputFile = urllib.request.urlretrieve(url, cacheFileName) |
| 94 |
else: |
| 95 |
if verboseMode == True: |
| 96 |
sys.stderr.write('Using cached ' + url + ' from ' + cacheFileName + ' ...\n') |
| 97 |
|
| 98 |
return open(cacheFileName, 'rb') |
| 99 |
|
| 100 |
|
| 101 |
# ###### Get URL of I-D metadata ############################################ |
| 102 |
def getMetadata(document : str) -> tuple[str,list[dict[str,str]]]: |
| 103 |
authorList : list[dict[str,str]] = [ ] |
| 104 |
|
| 105 |
# ====== Find latest version ============================================= |
| 106 |
if not re.match(r'^.*-[0-9][0-9]$', document): |
| 107 |
if document[0:3] == 'RFC': |
| 108 |
datatrackerURL = datatrackerPrefix + document.lower() + '/bibtex/' |
| 109 |
else: |
| 110 |
datatrackerURL = datatrackerPrefix + document.lower() + '/99/bibtex/' |
| 111 |
datatrackerStatus = fetch(datatrackerURL).readlines() |
| 112 |
|
| 113 |
numberRE : Final[re.Pattern[str]] = re.compile(r'^(number[ \t]*=[ \t]*\{)([^ ]*)-([0-9]+)\},$') |
| 114 |
authorRE : Final[re.Pattern[str]] = re.compile(r'^([ \t]*author[ \t]*=[ \t]*{)(.*)(})') |
| 115 |
for line in datatrackerStatus: |
| 116 |
lineStr : str = line.decode('utf-8').strip() |
| 117 |
match : re.Match[str] | None = numberRE.match(lineStr) |
| 118 |
if match is not None: |
| 119 |
name = match.group(2) |
| 120 |
lastestVersion = match.group(3) |
| 121 |
document = name + '-' + lastestVersion |
| 122 |
sys.stderr.write('Latest version of ' + name + ' is ' + lastestVersion + ' => ' + document + '\n') |
| 123 |
|
| 124 |
# ====== Find author list ========================================== |
| 125 |
else: |
| 126 |
match = authorRE.match(lineStr) |
| 127 |
if match is not None: |
| 128 |
names : list[str] = match.group(2).split(' and ') |
| 129 |
for name in names: |
| 130 |
# Work-around for lower-case first character in name: |
| 131 |
if len(name) > 0: |
| 132 |
name = name[0].upper() + name[1:] |
| 133 |
fullname : str = re.sub(r'^(Professor |Dr\. )', '', |
| 134 |
re.sub(r' ([A-Z]) ', ' \\1. ', |
| 135 |
re.sub(r'(\.)([A-Z])', '. \\2', name))) |
| 136 |
n : list[str] = fullname.split(' ') |
| 137 |
surname : str = n[len(n) - 1] |
| 138 |
initials : str = '' |
| 139 |
for i in range(0, len(n) - 1): |
| 140 |
initials = initials + n[i][0] + '.' |
| 141 |
# if (initials == '') or (fullname.find('@') != -1): |
| 142 |
# sys.stderr.write('WARNING: Bad author entry in ' + document + ': ' + fullname + '\n') |
| 143 |
authorList.append( |
| 144 |
{ |
| 145 |
'fullname': fullname, |
| 146 |
'initials': initials, |
| 147 |
'surname': surname |
| 148 |
} |
| 149 |
) |
| 150 |
# print(authorList) |
| 151 |
|
| 152 |
url : Final[str] = draftPrefix + document + '.xml' |
| 153 |
|
| 154 |
return url, authorList |
| 155 |
|
| 156 |
|
| 157 |
# ###### Get BibTeX from IETF document ###################################### |
| 158 |
def getBibTeXForIETFDocument(document : str) -> None: |
| 159 |
for blacklistEntry in blacklistTable: |
| 160 |
if document == blacklistEntry: |
| 161 |
sys.stderr.write('NOTE: ' + document + ' is blacklisted due to bad metadata in XML file. Skipping.\n') |
| 162 |
return |
| 163 |
|
| 164 |
issn : str | None = None |
| 165 |
documentType : str | None = None |
| 166 |
number : str | None = None |
| 167 |
institution : str | None = None |
| 168 |
note : str | None = None |
| 169 |
language : str = 'english' |
| 170 |
authorList : xml.dom.minicompat.NodeList[xml.dom.minidom.Element] = xml.dom.minicompat.NodeList() |
| 171 |
# Sequence[xml.dom.minidom.Element] = xml.dom.minicompat.NodeList() |
| 172 |
authorRegExpList : list[str] = [ ] |
| 173 |
unsortedAuthorList : list[dict[str,str]] = [ ] |
| 174 |
sortedAuthorList : list[dict[str,str]] = [ ] |
| 175 |
fullAuthorList : list[str] = [ ] |
| 176 |
|
| 177 |
|
| 178 |
# ====== Get information from BibTeX file ================================ |
| 179 |
# The IETF-provided BibTeX file has: |
| 180 |
# - Information about the latest version |
| 181 |
# - More accurate author information, but unordered |
| 182 |
# - But *not* the full date |
| 183 |
url : str = '' |
| 184 |
match : re.Match[str] | None = re.match(r'^draft-(.*)$', document) |
| 185 |
if match is not None: |
| 186 |
url, unsortedAuthorList = getMetadata(document) |
| 187 |
documentType = 'Internet Draft' |
| 188 |
number = match.group(1) |
| 189 |
match = re.match(r'^draft-ietf-(.*)$', document) |
| 190 |
if match is not None: |
| 191 |
institution = 'IETF' |
| 192 |
else: |
| 193 |
institution = 'IETF, Individual Submission' |
| 194 |
# note = 'Work in Progress' |
| 195 |
|
| 196 |
if url == '': |
| 197 |
match = re.match(r'^[Rr][Ff][Cc]([0-9]*)$', document) |
| 198 |
if match is not None: |
| 199 |
url, unsortedAuthorList = getMetadata(document) |
| 200 |
documentType = 'RFC' |
| 201 |
number = match.group(1) |
| 202 |
issn = '2070-1721' |
| 203 |
institution = 'IETF' |
| 204 |
document = documentType + number |
| 205 |
rfcNumber : int = int(number) |
| 206 |
url = rfcPrefix + '{0:04d}'.format(rfcNumber) + '.xml' |
| 207 |
|
| 208 |
if url == '': |
| 209 |
sys.stderr.write('ERROR: Unknown document type ' + document + '!\n') |
| 210 |
sys.exit(1) |
| 211 |
|
| 212 |
|
| 213 |
# ====== Get document information from XML file ========================== |
| 214 |
# The IETF-provided XML file has: |
| 215 |
# - Quite inaccurate author information, only ASCII names |
| 216 |
# - Inaccurate date, but ordered |
| 217 |
# - Type information |
| 218 |
try: |
| 219 |
xmlFile : BinaryIO = fetch(url) |
| 220 |
xmlDocument : xml.dom.minidom.Document = xml.dom.minidom.parse(xmlFile) |
| 221 |
except Exception as e: |
| 222 |
sys.stderr.write('ERROR: Failed to get XML information from ' + url + ': ' + str(e) + '!\n') |
| 223 |
sys.exit(1) |
| 224 |
|
| 225 |
# ------ Get authors list ------------------------------------------------ |
| 226 |
# The BibTeX file information is invalid, so use the less accurate |
| 227 |
# information from the XML file instead:+ |
| 228 |
|
| 229 |
# Try to read the actual draft XML file first: |
| 230 |
frontList : xml.dom.minicompat.NodeList[xml.dom.minidom.Element] = \ |
| 231 |
xmlDocument.getElementsByTagName('front') |
| 232 |
|
| 233 |
if frontList is not None: |
| 234 |
authorList = frontList[0].getElementsByTagName('author') |
| 235 |
else: |
| 236 |
# Else, try to read the reference XML file: |
| 237 |
authorList = xmlDocument.getElementsByTagName('author') |
| 238 |
if len(authorList) == 0: |
| 239 |
sys.stderr.write('ERROR: It seems that the XML file ' + url + ' does not exist. Wrong document name?\n') |
| 240 |
sys.exit(1) |
| 241 |
|
| 242 |
for authorListEntry in authorList: |
| 243 |
if not 'fullname' in authorListEntry.attributes: |
| 244 |
continue |
| 245 |
# print(authorListEntry.toxml()) |
| 246 |
# print('fullname=', authorListEntry.attributes['fullname'].value) |
| 247 |
# print('initials=', authorListEntry.attributes['initials'].value[0]) |
| 248 |
# print('surname=', authorListEntry.attributes['surname'].value) |
| 249 |
if authorListEntry.attributes['fullname'].value.find('@') != -1: |
| 250 |
sys.stderr.write('ERROR: Bad author entry in ' + document + ': ' + authorListEntry.attributes['fullname'].value + '\n') |
| 251 |
sys.exit(1) |
| 252 |
if authorListEntry.attributes['fullname'].value[1] == '.': |
| 253 |
authorRegExp = authorListEntry.attributes['initials'].value[0] + r'[a-zA-Z][a-zA-Z\s\.\- ]*' + \ |
| 254 |
authorListEntry.attributes['surname'].value |
| 255 |
else: |
| 256 |
authorRegExp = authorListEntry.attributes['fullname'].value |
| 257 |
authorRegExpList.append(authorRegExp) |
| 258 |
fullAuthorList.append(authorListEntry.attributes['fullname'].value) |
| 259 |
# print('authorRegExpList=', authorRegExpList) |
| 260 |
# print('fullAuthorList=', fullAuthorList) |
| 261 |
|
| 262 |
# ------ Get sorted author list from unsorted author list ---------------- |
| 263 |
if unsortedAuthorList is not None: |
| 264 |
# sortedAuthorList = [ ] |
| 265 |
fullAuthorList = [ ] |
| 266 |
for authorListEntry in authorList: |
| 267 |
if not 'fullname' in authorListEntry.attributes: |
| 268 |
continue |
| 269 |
found = False |
| 270 |
for a in unsortedAuthorList: |
| 271 |
if (('surname' in authorListEntry.attributes) and |
| 272 |
('initials' in authorListEntry.attributes) and |
| 273 |
(authorListEntry.attributes['surname'].value == a['surname']) and |
| 274 |
(authorListEntry.attributes['initials'].value[0] == a['initials'][0])): |
| 275 |
# sortedAuthorList.append({ |
| 276 |
# 'fullname': a['fullname'], |
| 277 |
# 'initials': a['initials'], |
| 278 |
# 'surname': a['surname'] |
| 279 |
# }) |
| 280 |
# sortedAuthorList.append(authorListEntry) |
| 281 |
fullAuthorList.append(a['fullname']) |
| 282 |
found = True |
| 283 |
break |
| 284 |
|
| 285 |
if not found: |
| 286 |
# sortedAuthorList.append({ |
| 287 |
# 'fullname': authorListEntry.attributes['fullname'].value, |
| 288 |
# 'initials': authorListEntry.attributes['initials'].value, |
| 289 |
# 'surname': authorListEntry.attributes['surname'].value |
| 290 |
# }) |
| 291 |
|
| 292 |
fullAuthorList.append(re.sub(r' ([A-Z]) ', ' \\1. ', |
| 293 |
re.sub(r'(\.)([A-Z])', '. \\2', |
| 294 |
re.sub(r'^([A-Z]) ', '\\1. ', authorListEntry.attributes['fullname'].value)))) |
| 295 |
# print('fullAuthorList=', fullAuthorList) |
| 296 |
|
| 297 |
|
| 298 |
# ------ Get date -------------------------------------------------------- |
| 299 |
dateList = xmlDocument.getElementsByTagName('date') |
| 300 |
month : int = 0 |
| 301 |
try: |
| 302 |
for monthName in monthNameTable: |
| 303 |
month = month + 1 |
| 304 |
if monthName == dateList[0].attributes['month'].value: |
| 305 |
break |
| 306 |
except: |
| 307 |
month = 0 |
| 308 |
try: |
| 309 |
day : int = int(dateList[0].attributes['day'].value) |
| 310 |
except: |
| 311 |
day = 0 |
| 312 |
try: |
| 313 |
year : int = int(dateList[0].attributes['year'].value) |
| 314 |
except: # Some RFCs have some garbage before the year content. |
| 315 |
l : Final[int] = len(dateList[0].attributes['year'].value) |
| 316 |
year = int(dateList[0].attributes['year'].value[l-4:l]) |
| 317 |
# print(day,month,year) |
| 318 |
|
| 319 |
# ------ Get title ------------------------------------------------------- |
| 320 |
titleList = xmlDocument.getElementsByTagName('title') |
| 321 |
title = titleList[0].childNodes[0].data |
| 322 |
title = title.strip().replace(' (', '~(') |
| 323 |
title = title.strip().replace(' - ', ' -- ') |
| 324 |
# print(title) |
| 325 |
|
| 326 |
# ------ Get type -------------------------------------------------------- |
| 327 |
seriesInfoList = xmlDocument.getElementsByTagName('seriesInfo') |
| 328 |
series = None |
| 329 |
name = None |
| 330 |
doi = None |
| 331 |
for seriesInfo in seriesInfoList: |
| 332 |
if seriesInfo.attributes['name'].value in ['RFC', 'Internet-Draft']: |
| 333 |
series = seriesInfo.attributes['name'].value |
| 334 |
name = seriesInfo.attributes['value'].value |
| 335 |
elif seriesInfo.attributes['name'].value == 'DOI': |
| 336 |
doi = seriesInfo.attributes['value'].value |
| 337 |
#print(series, name, doi) |
| 338 |
|
| 339 |
# ------ Get URL --------------------------------------------------------- |
| 340 |
formatList = xmlDocument.getElementsByTagName('format') |
| 341 |
try: |
| 342 |
url = formatList[0].attributes['target'].value |
| 343 |
except: |
| 344 |
if name is not None: |
| 345 |
if documentType == 'RFC': |
| 346 |
url = 'https://www.rfc-editor.org/rfc/rfc' + name + '.txt' |
| 347 |
else: |
| 348 |
url = 'https://tools.ietf.org/id/' + name + '.txt' |
| 349 |
|
| 350 |
# For I-Ds, use a secure URL instead of HTTP: |
| 351 |
url = url.replace('http://www.rfc-editor.org/rfc/', |
| 352 |
'https://www.rfc-editor.org/rfc/') |
| 353 |
url = url.replace('http://www.ietf.org/internet-drafts/', |
| 354 |
'https://tools.ietf.org/id/') |
| 355 |
# Fix redirect URL: |
| 356 |
url = url.replace('https://www.ietf.org/internet-drafts/', |
| 357 |
'https://tools.ietf.org/id/') |
| 358 |
|
| 359 |
# ------ Get abstract ---------------------------------------------------- |
| 360 |
abstractList = xmlDocument.getElementsByTagName('t') |
| 361 |
abstract = None |
| 362 |
try: |
| 363 |
abstract = abstractList[0].childNodes[0].data |
| 364 |
except: |
| 365 |
pass |
| 366 |
# print('A=',abstract,'.') |
| 367 |
|
| 368 |
if abstract is not None: |
| 369 |
abstract = abstract.strip().replace('\t', ' ') |
| 370 |
abstract = abstract.strip().replace('\n', ' ') |
| 371 |
abstract = abstract.strip().replace(' (', '~(') |
| 372 |
abstract = abstract.strip().replace(' - ', ' -- ') |
| 373 |
abstract = abstract.strip().replace('i.e. ', 'i.e.\\ ') |
| 374 |
abstract = abstract.strip().replace('e.g. ', 'e.g.\\ ') |
| 375 |
abstract = abstract.strip().replace(' [STANDARDS-TRACK]','') |
| 376 |
abstract = re.sub(r'(RFC|STD)( )([0-9]+)', '\\1~\\3', abstract.strip()) |
| 377 |
|
| 378 |
abstract = abstract.replace('</t><t>', '\n') |
| 379 |
while True: |
| 380 |
oldLength = len(abstract) |
| 381 |
abstract = abstract.strip().replace(' ', ' ') |
| 382 |
newLength = len(abstract) |
| 383 |
if oldLength == newLength: |
| 384 |
break |
| 385 |
|
| 386 |
# ====== Get full author list from text file ================================ |
| 387 |
try: |
| 388 |
txtFile = fetch(url) |
| 389 |
except Exception as e: |
| 390 |
sys.stderr.write('ERROR: Failed to get document from ' + url + ': ' + str(e) + '!\n') |
| 391 |
sys.exit(1) |
| 392 |
|
| 393 |
inAuthorsSection = False |
| 394 |
foundDate = False |
| 395 |
line = txtFile.readline() |
| 396 |
lineNumber = 0 |
| 397 |
while line: |
| 398 |
lineNumber = lineNumber + 1 |
| 399 |
|
| 400 |
# ====== RFC category ================================================= |
| 401 |
if lineNumber < 30: |
| 402 |
if re.search(r'^Category:', line.decode().strip()): |
| 403 |
match = re.match(r'^Category: (.*)[ ][ ].*$', line.decode().strip()) |
| 404 |
if match is not None: |
| 405 |
category = match.group(1).strip() |
| 406 |
if documentType == 'RFC': |
| 407 |
if category != 'Experimental': |
| 408 |
documentType = category + ' RFC' |
| 409 |
if foundDate == False: |
| 410 |
match = re.match(r'^.*(January|February|March|April|May|June|July|August|September|October|November|December)( [0-9]+[,]|)[ ]*([0-9][0-9][0-9][0-9])$', line.decode().strip()) |
| 411 |
# print(m,line.decode().strip()) |
| 412 |
if match is not None: |
| 413 |
foundDate = True |
| 414 |
|
| 415 |
# ====== Get year ============================================ |
| 416 |
newYear = int(match.group(3)) |
| 417 |
if newYear != year: |
| 418 |
if verboseMode == True: |
| 419 |
sys.stderr.write('Fix: Year ' + str(year) + ' -> ' + str(newYear) + '\n') |
| 420 |
year = newYear |
| 421 |
|
| 422 |
# ====== Get month =========================================== |
| 423 |
newMonth = 0 |
| 424 |
for monthName in monthNameTable: |
| 425 |
newMonth = newMonth + 1 |
| 426 |
if monthName == match.group(1): |
| 427 |
break |
| 428 |
if newMonth != month: |
| 429 |
if verboseMode == True: |
| 430 |
sys.stderr.write('Fix: Month ' + str(month) + ' -> ' + str(newMonth) + '\n') |
| 431 |
month = newMonth |
| 432 |
|
| 433 |
# ====== Get day ============================================= |
| 434 |
m2 = re.match(r'.* ([0-9]+) ' + monthNameTable[month - 1] + ' ' + str(year) + '$', line.decode().strip()) |
| 435 |
if m2 is not None: # Format: <Day> <Month>, <Year> |
| 436 |
newDay = int(m2.group(1)) |
| 437 |
else: # Format: <Month> <Day>, <Year> |
| 438 |
try: |
| 439 |
newDay = int(match.group(2).replace(',', '')) |
| 440 |
except: |
| 441 |
newDay = 0 |
| 442 |
if ((newDay != 0) and (newDay != day)): |
| 443 |
if verboseMode == True: |
| 444 |
sys.stderr.write('Fix: Day ' + str(day) + ' -> ' + str(newDay) + '\n') |
| 445 |
day = newDay |
| 446 |
|
| 447 |
# ====== Author ================================================= |
| 448 |
else: |
| 449 |
# Author is right-adjusted block |
| 450 |
block = re.sub('.*[ \t][ \t]', '', line.decode().strip()) |
| 451 |
i = 0 |
| 452 |
for authorRegExpListEntry in authorRegExpList: |
| 453 |
match = re.match(r'^(.*)(' + authorRegExpListEntry + ')([\t ]*|$)', block) |
| 454 |
if match is not None: |
| 455 |
if len(match.group(2)) >= len(fullAuthorList[i]): |
| 456 |
fullAuthorList[i] = str(match.group(2)) |
| 457 |
i = i + 1 |
| 458 |
|
| 459 |
|
| 460 |
# ====== Authors section ============================================== |
| 461 |
if len(authorRegExpList) < 1: |
| 462 |
line = txtFile.readline() |
| 463 |
continue |
| 464 |
if inAuthorsSection == True: |
| 465 |
try: |
| 466 |
# Sometimes, there may be some strange letters inside -> decode fails. |
| 467 |
d = line.decode().strip() |
| 468 |
except: |
| 469 |
d='' # Just ignore not-decodable stuff for now. |
| 470 |
|
| 471 |
# ------ Check for end of author section --------------------------- |
| 472 |
if re.search(r'^[0-9\.]* ', d): |
| 473 |
# print('End of Author Section:', line) |
| 474 |
inAuthorsSection = False |
| 475 |
|
| 476 |
# ------ Parse author section -------------------------------------- |
| 477 |
elif not re.search(r'^[\s]*$', d): |
| 478 |
i = 0 |
| 479 |
for author in authorRegExpList: |
| 480 |
match = re.match(r'^(.*)(' + author + ')([\t ].*|,.*|)$', line.decode().strip()) |
| 481 |
# print(line.strip(), i, m, author) |
| 482 |
if match is not None: |
| 483 |
if len(match.group(2)) >= len(fullAuthorList[i]): |
| 484 |
fullAuthorList[i] = str(match.group(2)) |
| 485 |
# print('!!! A2: ', line.strip(), i, m, author) |
| 486 |
i = i + 1 |
| 487 |
|
| 488 |
else: |
| 489 |
try: |
| 490 |
match = re.search(r'(^([0-9\.]*|[A-Z]\.)[ \t]+.*|^)(Editors|Authors|Authors\'[ \t]+Addresses|Author\'s[ \t]+Address|Editor\'s[ \t]+Address|Author[ \t]+Information).*$', line.decode().strip(), re.IGNORECASE) |
| 491 |
if match is not None: |
| 492 |
# Check whether line is in table of contents |
| 493 |
m2 = re.search(r'\. \.[ \t]*[0-9]+$', line.decode().strip()) |
| 494 |
if m2 is None: |
| 495 |
# print('Begin of Author Section:', line) |
| 496 |
inAuthorsSection = True |
| 497 |
except: |
| 498 |
pass |
| 499 |
|
| 500 |
line = txtFile.readline() |
| 501 |
|
| 502 |
|
| 503 |
# ====== Fix author list via author fix file ================================ |
| 504 |
csv.register_dialect('authors-fix', delimiter=' ', quoting=csv.QUOTE_MINIMAL, skipinitialspace=True) |
| 505 |
inputCSV = None |
| 506 |
if authorsFixFile == 'DEFAULT': |
| 507 |
authorsFixFileList = [ 'authors-fix.list', '/usr/share/doc/bibtexconv/examples/authors-fix.list' ] |
| 508 |
elif authorsFixFile is not None: |
| 509 |
authorsFixFileList = [ authorsFixFile ] |
| 510 |
else: |
| 511 |
authorsFixFileList = [ ] |
| 512 |
for authorsFixFileName in authorsFixFileList: |
| 513 |
if os.path.exists(authorsFixFileName): |
| 514 |
try: |
| 515 |
inputFile = codecs.open(authorsFixFileName, 'r', 'utf-8') |
| 516 |
inputCSV = csv.reader(inputFile, dialect='authors-fix') |
| 517 |
break |
| 518 |
except: |
| 519 |
pass |
| 520 |
|
| 521 |
if ((authorsFixFile is not None) and (inputCSV is None)): |
| 522 |
sys.stderr.write('ERROR: Unable to load authors fix file. Use option --authors-fix-file=FILE or --no-authors-fix-file!\n') |
| 523 |
sys.exit(1) |
| 524 |
elif inputCSV is not None: |
| 525 |
if verboseMode == True: |
| 526 |
sys.stderr.write('NOTE: Using authors fix file ' + authorsFixFileName + '\n') |
| 527 |
|
| 528 |
for row in inputCSV: |
| 529 |
for i in range(0, len(fullAuthorList), 1): |
| 530 |
if row[0] == fullAuthorList[i]: |
| 531 |
if verboseMode == True: |
| 532 |
sys.stderr.write('Fix(' + authorsFixFileName + '): ' + fullAuthorList[i] + ' -> ' + row[1] + '\n') |
| 533 |
fullAuthorList[i] = row[1] |
| 534 |
break |
| 535 |
|
| 536 |
|
| 537 |
# ====== Check =========================================================== |
| 538 |
if foundDate == False: |
| 539 |
sys.stderr.write('WARNING: Unable to find date of document ' + document + '!\n') |
| 540 |
|
| 541 |
|
| 542 |
# ====== Print result ==================================================== |
| 543 |
sys.stdout.write('@TechReport{ ' + document + ',\n') |
| 544 |
sys.stdout.write('\tauthor = "') |
| 545 |
isFirstAuthor = True |
| 546 |
for author in fullAuthorList: |
| 547 |
if isFirstAuthor == True: |
| 548 |
isFirstAuthor = False |
| 549 |
else: |
| 550 |
sys.stdout.write(' and ') |
| 551 |
sys.stdout.write(author) |
| 552 |
sys.stdout.write('",\n') |
| 553 |
|
| 554 |
if title is not None: |
| 555 |
sys.stdout.write('\ttitle = "{' + title + '}",\n') |
| 556 |
if documentType is not None: |
| 557 |
sys.stdout.write('\ttype = "' + documentType + '",\n') |
| 558 |
if name is not None: |
| 559 |
sys.stdout.write('\tnumber = "' + name + '",\n') |
| 560 |
|
| 561 |
if day > 0: |
| 562 |
sys.stdout.write('\tday = "' + str(day) + '",\n') |
| 563 |
if ((month >= 1) and (month <= 12)): |
| 564 |
sys.stdout.write('\tmonth = ' + monthIDTable[month - 1] + ',\n') |
| 565 |
sys.stdout.write('\tyear = "' + str(year) + '",\n') |
| 566 |
|
| 567 |
if institution is not None: |
| 568 |
sys.stdout.write('\tinstitution = "' + institution + '",\n') |
| 569 |
sys.stdout.write('\tlanguage = "' + language + '",\n') |
| 570 |
if issn is not None: |
| 571 |
sys.stdout.write('\tissn = "' + issn + '",\n') |
| 572 |
if doi is not None: |
| 573 |
sys.stdout.write('\tdoi = "' + doi + '",\n') |
| 574 |
if note is not None: |
| 575 |
sys.stdout.write('\tnote = "' + note + '",\n') |
| 576 |
if abstract is not None: |
| 577 |
sys.stdout.write('\tabstract = "{' + abstract + '}",\n') |
| 578 |
sys.stdout.write('\turl = "' + url + '"\n') |
| 579 |
|
| 580 |
sys.stdout.write('}\n\n') |
| 581 |
|
| 582 |
|
| 583 |
|
| 584 |
# ###### Main program ####################################################### |
| 585 |
if len(sys.argv) < 2: |
| 586 |
sys.stderr.write('Usage: ietf2bibtex [--quiet|--verbose] [--authors-fix-file=FILE|--no-authors-fix-file] document ...\n') |
| 587 |
sys.exit(1) |
| 588 |
|
| 589 |
for i in range(1, len(sys.argv)): |
| 590 |
if sys.argv[i] == '--quiet': |
| 591 |
verboseMode = False |
| 592 |
elif sys.argv[i] == '--verbose': |
| 593 |
verboseMode = True |
| 594 |
elif sys.argv[i] == '--no-authors-fix-file': |
| 595 |
authorsFixFile = None |
| 596 |
elif sys.argv[i][0:19] == '--authors-fix-file=': |
| 597 |
authorsFixFile = sys.argv[i][19:] |
| 598 |
i = i + 1 |
| 599 |
else: |
| 600 |
getBibTeXForIETFDocument(sys.argv[i]) |