| 1 |
#! /usr/bin/env python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
################################################################################## |
| 4 |
# |
| 5 |
# getmref.py - gets the references links to MathSciNet through the BatchMRef: |
| 6 |
# https://mathscinet.ams.org/batchmref?qdata=xmldocument |
| 7 |
# |
| 8 |
# Copyright (C) 2017 Sigitas Tolusis, VTeX Ltd., Jim Pitman, Dept. Statistics, |
| 9 |
# U.C. Berkeley and Lolita Tolene, VTeX Ltd. |
| 10 |
# E-mail: [email protected] |
| 11 |
# http://www.stat.berkeley.edu/users/pitman |
| 12 |
# |
| 13 |
# This program is free software; you can redistribute it and/or |
| 14 |
# modify it under the terms of the GNU General Public License |
| 15 |
# as published by the Free Software Foundation; either version 2 |
| 16 |
# of the License, or (at your option) any later version. |
| 17 |
# |
| 18 |
# This program is distributed in the hope that it will be useful, |
| 19 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 20 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 21 |
# GNU General Public License for more details. |
| 22 |
# |
| 23 |
# Requires: |
| 24 |
# - python ver. >=2.2 |
| 25 |
# - [ for option --enc=auto ] |
| 26 |
# Universal Encoding Detector library, written by Mark Pilgrim. |
| 27 |
# |
| 28 |
# Usage: |
| 29 |
# getmref.py <bbl or tex file> |
| 30 |
# |
| 31 |
# Program (description): |
| 32 |
# - makes inputfile copy to <inputfilename>.getmref.bak; |
| 33 |
# - for each successful bibitem reference search adds line \MR{<mrid>}, |
| 34 |
# where <mrid> is data from XML tag <mrid> without front symbols "MR"; |
| 35 |
# - writes all adds to <inputfilename>; |
| 36 |
# - generates log file <inputfilename>.getmref.log; |
| 37 |
# - writes to stdout log info |
| 38 |
# |
| 39 |
# Changes: |
| 40 |
# 2004/04/26 - \bibitem line removed from the query |
| 41 |
# 2017/01/12 - input file may contain 'amsrefs', 'bibtex' and 'tex' type |
| 42 |
# references (all at once); |
| 43 |
# input references can be formatted as 'amsrefs', 'bibtex', |
| 44 |
# 'tex' or 'html' type references |
| 45 |
# |
| 46 |
# |
| 47 |
################################################################################## |
| 48 |
|
| 49 |
__version__ = "GetMRef, v2.4" |
| 50 |
|
| 51 |
import sys |
| 52 |
import os |
| 53 |
import re |
| 54 |
import string |
| 55 |
import urllib |
| 56 |
import urllib2 |
| 57 |
import ssl |
| 58 |
import shutil |
| 59 |
import logging |
| 60 |
from time import time, sleep |
| 61 |
from xml.dom.minidom import parseString |
| 62 |
from xml.parsers.expat import ExpatError |
| 63 |
|
| 64 |
BASICFORMATTER = logging.Formatter('%(message)s') |
| 65 |
DEBUGFORMATTER = logging.Formatter('%(asctime)s %(levelname)s %(message)s') |
| 66 |
|
| 67 |
log = logging.getLogger(__name__) |
| 68 |
log.addHandler(logging.NullHandler()) |
| 69 |
flog = slog = log |
| 70 |
|
| 71 |
|
| 72 |
class RefTypes(object): |
| 73 |
""" This class declares recognized bibliography reference formats |
| 74 |
|
| 75 |
Formats description |
| 76 |
------------------- |
| 77 |
Source: only AMS |
| 78 |
"tex": LaTeX code without any specific beginning/ending; |
| 79 |
MR number is given in plain text |
| 80 |
"html": <a href="http://www.ams.org/mathscinet-getitem?mr=7digits"> |
| 81 |
7digits |
| 82 |
</a> |
| 83 |
|
| 84 |
Source: only user |
| 85 |
"bibitem": \bibitem[<name-year info>]{<cite_key>} |
| 86 |
... |
| 87 |
\MR{<7 digits>} |
| 88 |
\endbibitem, |
| 89 |
where '[<name-year info>]' and '\endbibitem' are optional |
| 90 |
Requires environment |
| 91 |
\begin{thebibliography}{<ref no>} |
| 92 |
... |
| 93 |
\end{thebibliography} |
| 94 |
|
| 95 |
Source: AMS and user |
| 96 |
"bibtex": @<ref type>{<cite_key>, |
| 97 |
<key1>={<value1>}, |
| 98 |
<key2>={<value2>}, |
| 99 |
MRNUMBER={<7 digits>} |
| 100 |
...} |
| 101 |
"amsrefs": \bib{<cite_key>}{<ref type>}{ |
| 102 |
<key1>={<value1>}, |
| 103 |
<key2>={<value2>}, |
| 104 |
review={\MR{<7 digits>}} |
| 105 |
...} |
| 106 |
Requires environment |
| 107 |
\begin{biblist} |
| 108 |
... |
| 109 |
\end{biblist} |
| 110 |
""" |
| 111 |
|
| 112 |
TEX = "tex" |
| 113 |
BIBITEM = "bibitem" |
| 114 |
IMS = "ims" |
| 115 |
BIBTEX = "bibtex" |
| 116 |
AMSREFS = "amsrefs" |
| 117 |
HTML = "html" |
| 118 |
|
| 119 |
# Reference input formats |
| 120 |
ITYPES = (BIBITEM, BIBTEX, AMSREFS) |
| 121 |
|
| 122 |
# Reference output formats |
| 123 |
OTYPES = (TEX, BIBTEX, IMS, AMSREFS, HTML) |
| 124 |
|
| 125 |
|
| 126 |
class LessThanFilter(logging.Filter): |
| 127 |
""" This class allows to add an upper bound to the logged messages |
| 128 |
|
| 129 |
Example |
| 130 |
------- |
| 131 |
One needs to log all non-error messages to stdout, and all errors |
| 132 |
(higher level) only to stderr |
| 133 |
""" |
| 134 |
|
| 135 |
def __init__(self, exclusive_maximum, name=""): |
| 136 |
super(LessThanFilter, self).__init__(name) |
| 137 |
self.max_level = exclusive_maximum |
| 138 |
|
| 139 |
def filter(self, record): |
| 140 |
# A non-zero return means we log this message |
| 141 |
return 1 if record.levelno <= self.max_level else 0 |
| 142 |
|
| 143 |
|
| 144 |
class FilesHandler(RefTypes): |
| 145 |
""" This class unites methods and attributes related to |
| 146 |
files I/O actions """ |
| 147 |
|
| 148 |
IN = 'in' |
| 149 |
BAK = 'bak' |
| 150 |
OUT = 'out' |
| 151 |
DATA = 'data' |
| 152 |
TMP = 'tmp' |
| 153 |
AUX = 'aux' |
| 154 |
BIB = 'bib' |
| 155 |
HTML = 'html' |
| 156 |
LOG = 'log' |
| 157 |
ERR = 'err' |
| 158 |
|
| 159 |
# File status map: |
| 160 |
# if True file will be open until closed; |
| 161 |
# if False it will be opened on demand |
| 162 |
FILE_STATUS = {OUT: True, |
| 163 |
LOG: False, |
| 164 |
ERR: False, |
| 165 |
DATA: True, |
| 166 |
BIB: True, |
| 167 |
AUX: True, |
| 168 |
HTML: True, |
| 169 |
TMP: False} |
| 170 |
|
| 171 |
READ = 'r' |
| 172 |
WRITE = 'w' |
| 173 |
|
| 174 |
GMR_SUFFIX = 'getmref' |
| 175 |
|
| 176 |
def __init__(self, infile, outputtype): |
| 177 |
""" Initiate file handling methods and attributes |
| 178 |
|
| 179 |
Parameters |
| 180 |
---------- |
| 181 |
infile : str or None |
| 182 |
Path to input file |
| 183 |
outputtype : str or None |
| 184 |
Required bibliography reference output format type |
| 185 |
""" |
| 186 |
|
| 187 |
self.infile = infile |
| 188 |
self._basename = os.path.splitext(infile)[0] |
| 189 |
|
| 190 |
# Determining needed file types for given reference output type |
| 191 |
msg = ("The given references will be formatted in '%s' format. " |
| 192 |
% (outputtype if outputtype is not None else "orig")) |
| 193 |
|
| 194 |
unnecessary = [self.DATA, self.BIB, self.AUX, self.HTML] |
| 195 |
if outputtype in [self.BIBTEX, self.IMS]: |
| 196 |
unnecessary = [self.DATA, self.HTML] |
| 197 |
# Referring to 'BIB' file as 'DATA' |
| 198 |
self.DATA = self.BIB |
| 199 |
msg += "Additional files will be created: *.%s, *.%s" \ |
| 200 |
% (self.BIB, self.AUX) |
| 201 |
elif outputtype == self.HTML: |
| 202 |
unnecessary = [self.DATA, self.BIB, self.AUX] |
| 203 |
# Referring to 'HTML' file as 'DATA' |
| 204 |
self.DATA = self.HTML |
| 205 |
msg += "Additional file will be created: *.%s" % self.HTML |
| 206 |
elif outputtype in [self.TEX, self.AMSREFS]: |
| 207 |
unnecessary = [self.HTML, self.BIB, self.AUX] |
| 208 |
msg += "Additional file will be created: *.%s" % self.DATA |
| 209 |
|
| 210 |
self.files = dict() |
| 211 |
for suffix, status in self.FILE_STATUS.items(): |
| 212 |
# Deleting old files |
| 213 |
self._delete(suffix) |
| 214 |
if suffix in unnecessary: |
| 215 |
continue |
| 216 |
if status: |
| 217 |
self.open(suffix) |
| 218 |
continue |
| 219 |
self.files.update({suffix: self.get_fname(suffix)}) |
| 220 |
|
| 221 |
flog.info("File: %s" % infile) |
| 222 |
if not (os.path.isfile(infile) and os.path.exists(infile)): |
| 223 |
logging.shutdown() |
| 224 |
for suffix in self.FILE_STATUS: |
| 225 |
self.close_and_delete(suffix) |
| 226 |
raise ValueError("Provided source file does not exist! " |
| 227 |
"Please provide the valid one.") |
| 228 |
|
| 229 |
flog.debug("Workdir: %s" % os.path.abspath(os.path.dirname(infile))) |
| 230 |
flog.debug(msg) |
| 231 |
|
| 232 |
def set_fname(self, suffix): |
| 233 |
""" Set a filepath for a file with the provided suffix |
| 234 |
|
| 235 |
Parameters |
| 236 |
---------- |
| 237 |
suffix : str |
| 238 |
File suffix without punctuation |
| 239 |
|
| 240 |
Returns |
| 241 |
------- |
| 242 |
str |
| 243 |
""" |
| 244 |
return ("%s.%s.%s" % (self._basename, self.GMR_SUFFIX, suffix) |
| 245 |
if suffix != self.IN else self.infile) |
| 246 |
|
| 247 |
def get_fname(self, suffix): |
| 248 |
""" Get filepath of a file with the required suffix |
| 249 |
|
| 250 |
Parameters |
| 251 |
---------- |
| 252 |
suffix : str |
| 253 |
File suffix without punctuation |
| 254 |
|
| 255 |
Returns |
| 256 |
------- |
| 257 |
str |
| 258 |
If requested file is open, returning file object name, |
| 259 |
or the filepath otherwise |
| 260 |
""" |
| 261 |
target = self.files.get(suffix, self.set_fname(suffix)) |
| 262 |
if isinstance(target, file): |
| 263 |
return target.name |
| 264 |
return target |
| 265 |
|
| 266 |
def open(self, suffix, mask=WRITE): |
| 267 |
""" Open file for the selected action |
| 268 |
|
| 269 |
Parameters |
| 270 |
---------- |
| 271 |
suffix : str |
| 272 |
File suffix without punctuation |
| 273 |
mask : str |
| 274 |
Possible actions are read or write |
| 275 |
|
| 276 |
File is opened and file object is added to the dictionary |
| 277 |
for later access |
| 278 |
""" |
| 279 |
self.files.update({suffix: file(self.get_fname(suffix), mask)}) |
| 280 |
|
| 281 |
def read(self, suffix): |
| 282 |
""" Get the content of a file with the required suffix |
| 283 |
|
| 284 |
Parameters |
| 285 |
---------- |
| 286 |
suffix : str |
| 287 |
File suffix without punctuation |
| 288 |
|
| 289 |
Yields |
| 290 |
------ |
| 291 |
str |
| 292 |
""" |
| 293 |
with open(self.get_fname(suffix), self.READ) as ifile: |
| 294 |
for iline in ifile: |
| 295 |
yield iline |
| 296 |
|
| 297 |
def write(self, suffix, msg): |
| 298 |
""" Write to the file with the required suffix |
| 299 |
only if this file is open |
| 300 |
|
| 301 |
Parameters |
| 302 |
---------- |
| 303 |
suffix : str |
| 304 |
File suffix without punctuation |
| 305 |
msg : str |
| 306 |
""" |
| 307 |
target = self.files.get(suffix, None) |
| 308 |
if isinstance(target, file): |
| 309 |
target.write(msg) |
| 310 |
|
| 311 |
def close(self, suffix): |
| 312 |
""" Close the file with the required suffix |
| 313 |
|
| 314 |
Parameters |
| 315 |
---------- |
| 316 |
suffix : str |
| 317 |
File suffix without punctuation |
| 318 |
""" |
| 319 |
fileobj = self.files.get(suffix, "") |
| 320 |
if isinstance(fileobj, file): |
| 321 |
fileobj.close() |
| 322 |
|
| 323 |
def _delete(self, suffix): |
| 324 |
""" Delete the file with the required suffix |
| 325 |
|
| 326 |
Parameters |
| 327 |
---------- |
| 328 |
suffix : str |
| 329 |
File suffix without punctuation |
| 330 |
""" |
| 331 |
dfile = self.get_fname(suffix) |
| 332 |
try: |
| 333 |
os.unlink(dfile) |
| 334 |
flog.debug("Deleted: %s" % os.path.split(dfile)[1]) |
| 335 |
except OSError: |
| 336 |
if os.path.isfile(dfile) and os.path.exists(dfile): |
| 337 |
flog.exception("Can't remove file: %s" % dfile) |
| 338 |
|
| 339 |
def close_and_delete(self, suffix): |
| 340 |
""" Close and delete the file with the required suffix |
| 341 |
|
| 342 |
Parameters |
| 343 |
---------- |
| 344 |
suffix : str |
| 345 |
File suffix without punctuation |
| 346 |
""" |
| 347 |
self.close(suffix) |
| 348 |
self._delete(suffix) |
| 349 |
|
| 350 |
def close_files(self): |
| 351 |
""" Close all open files and logging instances, |
| 352 |
create backup of the input file and |
| 353 |
overwrite it with the new content, delete auxiliary files |
| 354 |
""" |
| 355 |
flog.debug("Closing files...") |
| 356 |
for suffix in self.files: |
| 357 |
self.close(suffix) |
| 358 |
|
| 359 |
self._delete(self.TMP) |
| 360 |
|
| 361 |
bfile = self.get_fname(self.BAK) |
| 362 |
if os.path.exists(bfile): |
| 363 |
shutil.copy2(self.infile, bfile) |
| 364 |
else: |
| 365 |
os.rename(self.infile, bfile) |
| 366 |
flog.debug("Created backup of the input file: %s" |
| 367 |
% os.path.split(bfile)[1]) |
| 368 |
|
| 369 |
ofile = self.get_fname(self.OUT) |
| 370 |
if os.path.exists(ofile): |
| 371 |
shutil.copy2(ofile, self.infile) |
| 372 |
self._delete(self.OUT) |
| 373 |
else: |
| 374 |
os.rename(ofile, self.infile) |
| 375 |
flog.debug("The input file is overwritten with: %s" |
| 376 |
% os.path.split(ofile)[1]) |
| 377 |
|
| 378 |
logging.shutdown() |
| 379 |
|
| 380 |
|
| 381 |
class RefHandler(RefTypes): |
| 382 |
""" This class unites methods and attributes related to bibliography |
| 383 |
reference format types and their content modifications """ |
| 384 |
|
| 385 |
# Bibliography environment |
| 386 |
BIBL_ENV = "environment" |
| 387 |
BIBL_BEGIN = "begin" |
| 388 |
BIBL_END = "end" |
| 389 |
|
| 390 |
# Declaration of typical reference type ending and |
| 391 |
# MR id format for this type |
| 392 |
FORMAT_PROPERTIES = { |
| 393 |
RefTypes.BIBTEX: { |
| 394 |
"ref_ending": "}", |
| 395 |
"mr_format": ",\nMRNUMBER={%s},\n" |
| 396 |
}, |
| 397 |
RefTypes.AMSREFS: { |
| 398 |
"ref_ending": "}", |
| 399 |
"mr_format": ",\nreview={\MR{%s}},\n" |
| 400 |
}, |
| 401 |
RefTypes.BIBITEM: { |
| 402 |
"ref_ending": "\\endbibitem", |
| 403 |
"mr_format": "\n\\MR{%s}\n" |
| 404 |
} |
| 405 |
} |
| 406 |
|
| 407 |
# Meaningful reference keys for AMS Batch MR Lookup query |
| 408 |
KEYS = {"0AUTH": ("author",), |
| 409 |
"1TTL": ("title", "maintitle"), |
| 410 |
"2JOUR": ("journal", "journaltitle", "fjournal", "booktitle"), |
| 411 |
"3VID": ("volume",), |
| 412 |
"4IID": ("number", "series"), |
| 413 |
"5PID": ("pages",), |
| 414 |
"6YNO": ("year", "date"), |
| 415 |
"7ISSN": ("issn", "isrn", "isbn")} |
| 416 |
|
| 417 |
PATTERN_KEY_VALUE = "^\s*([\w-]+)\s*=\s*(.*?)$" |
| 418 |
|
| 419 |
PATTERN_LINE_END = r'(\r?\n)+' |
| 420 |
PATTERN_PAR = r'(\r?\n){2}' |
| 421 |
|
| 422 |
PATTERN_BIBL_ENV = (r'\s*\\(?P<envstatus>begin|end)\s*' |
| 423 |
r'\{(thebibliography|biblist\*?)\}(.*)$') |
| 424 |
|
| 425 |
PATTERN_BIBRE = r'^\s*\\bibitem.*' |
| 426 |
PATTERN_BIBREF = (r'\s*\\bibitem\s*(?P<biblabel>\[.*?\])*?\s?' |
| 427 |
r'\{(?P<citekey>.*?)\}(?P<text>.*)$') |
| 428 |
PATTERN_BIBTEX = (r'^\s*(@\S+)(?<!@preamble)\s*' |
| 429 |
r'{(?P<citekey>\S+)\s*,(?P<text>.*)$') |
| 430 |
PATTERN_AMSREFS = r"\\bib\s*{(?P<citekey>.*)}\s*{(.*)}\s*{(?P<text>.*)$" |
| 431 |
|
| 432 |
def __init__(self, outputtype): |
| 433 |
""" Initiate reference handling methods and attributes |
| 434 |
|
| 435 |
Parameters |
| 436 |
---------- |
| 437 |
outputtype : str or None |
| 438 |
Required reference output format type |
| 439 |
""" |
| 440 |
|
| 441 |
self.outputtype = outputtype |
| 442 |
|
| 443 |
self.re_bibl_env = re.compile(self.PATTERN_BIBL_ENV) |
| 444 |
self.re_bibre = re.compile(self.PATTERN_BIBRE) |
| 445 |
self.re_bibreF = re.compile(self.PATTERN_BIBREF, re.S) |
| 446 |
self.re_bibtex = re.compile(self.PATTERN_BIBTEX, re.M) |
| 447 |
self.re_amsrefs = re.compile(self.PATTERN_AMSREFS, re.M) |
| 448 |
|
| 449 |
self.re_lineend = re.compile(self.PATTERN_LINE_END) |
| 450 |
self.re_par = re.compile(self.PATTERN_PAR) |
| 451 |
self.re_key_value = re.compile(self.PATTERN_KEY_VALUE, re.DOTALL) |
| 452 |
|
| 453 |
def find_reference(self, line): |
| 454 |
""" Identify reference environment or element by using regex patterns |
| 455 |
|
| 456 |
Parameters |
| 457 |
---------- |
| 458 |
line : str |
| 459 |
|
| 460 |
Returns |
| 461 |
------- |
| 462 |
str or None |
| 463 |
If match is found, returns the reference type, None otherwise |
| 464 |
dict |
| 465 |
Dictionary contains regex pattern group names and their matches |
| 466 |
|
| 467 |
The value of the key 'text' is the line part without user |
| 468 |
defined strings, such as citekey and biblabel, because they may |
| 469 |
contain some misleading information for BatchMRef query |
| 470 |
""" |
| 471 |
|
| 472 |
elems = {self.BIBL_ENV: self.re_bibl_env, |
| 473 |
self.BIBTEX: self.re_bibtex, |
| 474 |
self.AMSREFS: self.re_amsrefs} |
| 475 |
|
| 476 |
# BIBITEM search starts with an additional check |
| 477 |
# which other reference types doesn't have |
| 478 |
if self.re_bibre.search(line) is not None: |
| 479 |
elems = {self.BIBITEM: self.re_bibreF} |
| 480 |
|
| 481 |
for reftype, pattern in elems.items(): |
| 482 |
match = pattern.search(line) |
| 483 |
if match is not None: |
| 484 |
return reftype, match.groupdict() |
| 485 |
elif reftype == self.BIBITEM: |
| 486 |
# If final search for BIBITEM fails, it means that the typical |
| 487 |
# structure for this reference type is placed on several lines, |
| 488 |
# therefore the current line is prepended to the next input line |
| 489 |
return reftype, {"line": line} |
| 490 |
return None, dict() |
| 491 |
|
| 492 |
def extract_keys_data(self, lines): |
| 493 |
""" Extract values from selected keys in reference |
| 494 |
|
| 495 |
Parameters |
| 496 |
---------- |
| 497 |
lines : list |
| 498 |
|
| 499 |
Returns |
| 500 |
------- |
| 501 |
str |
| 502 |
Output contains extracted values separated by commas |
| 503 |
""" |
| 504 |
flog.debug(">> Extracting key values from reference") |
| 505 |
querystring = "" |
| 506 |
user_key = None |
| 507 |
found = list() |
| 508 |
for line in lines: |
| 509 |
match = self.re_key_value.search(line) |
| 510 |
if match: |
| 511 |
user_key, user_value = match.groups() |
| 512 |
user_key = user_key.lower() |
| 513 |
for key, value in sorted(self.KEYS.items()): |
| 514 |
if user_key in value and (user_key in found or key not in found): |
| 515 |
found.append(key) |
| 516 |
found.append(user_key) |
| 517 |
querystring += "%s, " % user_value.strip().rstrip(",")\ |
| 518 |
.strip().strip('"')\ |
| 519 |
.strip().rstrip("}")\ |
| 520 |
.lstrip("{").strip() |
| 521 |
break |
| 522 |
elif len(found) > 0 and found[-1] == user_key: |
| 523 |
querystring = "%s %s, " % (querystring.strip(", "), |
| 524 |
line.strip().rstrip(",").strip().strip('"') |
| 525 |
.strip().rstrip("}").lstrip("{") |
| 526 |
.strip().rstrip(",").strip()) |
| 527 |
|
| 528 |
return querystring.strip(", ") |
| 529 |
|
| 530 |
def insert_mrid(self, reftype, refstring, mrid): |
| 531 |
""" Format MR number according to the input reference format and |
| 532 |
append it to the input reference |
| 533 |
|
| 534 |
Parameters |
| 535 |
---------- |
| 536 |
reftype : str |
| 537 |
Determined input bibliography reference item type |
| 538 |
refstring : str |
| 539 |
Input bibliography reference item content |
| 540 |
mrid : str |
| 541 |
MR number returned by query to BatchMRef |
| 542 |
|
| 543 |
Returns |
| 544 |
------- |
| 545 |
str |
| 546 |
Output contains input bibliography reference element including |
| 547 |
according to reftype formatted mrid. |
| 548 |
""" |
| 549 |
properties = self.FORMAT_PROPERTIES.get(reftype, None) |
| 550 |
if properties is None: |
| 551 |
outstring = self.re_lineend.sub('\n', refstring) |
| 552 |
return '%s\\MR{%s}\n\n' % (outstring, mrid) |
| 553 |
|
| 554 |
mr_string = properties["mr_format"] % mrid |
| 555 |
ending_index = refstring.rfind(properties["ref_ending"]) |
| 556 |
if ending_index == -1: |
| 557 |
paragraph = self.re_par.search(refstring) |
| 558 |
if paragraph is not None: |
| 559 |
ending_index = paragraph.start() |
| 560 |
mr_string += "\n" |
| 561 |
|
| 562 |
if ending_index != -1: |
| 563 |
return "%s%s%s" % (refstring[:ending_index].strip().strip(","), |
| 564 |
mr_string, |
| 565 |
refstring[ending_index:].lstrip()) |
| 566 |
|
| 567 |
return refstring.strip() + mr_string + "\n" |
| 568 |
|
| 569 |
def insert_citekey(self, outref, citekey, biblabel, querystring): |
| 570 |
""" Add a cite key, extracted from an input reference item, |
| 571 |
to the reference content, returned by the query to BatchMRef |
| 572 |
(XML tag <outref>), in the required reference output format |
| 573 |
|
| 574 |
Parameters |
| 575 |
---------- |
| 576 |
outref : str or None |
| 577 |
Reference item content returned by the query to BatchMRef |
| 578 |
citekey : str |
| 579 |
Input bibliography reference item cite key |
| 580 |
biblabel : str or None |
| 581 |
Input bibliography reference item label, |
| 582 |
provided in optional parameter of reference type of BIBITEM |
| 583 |
querystring : str |
| 584 |
Input bibliography reference item formatted for query |
| 585 |
to BatchMRef |
| 586 |
|
| 587 |
Returns |
| 588 |
------- |
| 589 |
str or None |
| 590 |
Returned string is the outref including the citekey and |
| 591 |
the biblabel (if provided) if reference has been found in |
| 592 |
the AMS MR DB, else string is formatted according to the |
| 593 |
requested output type. |
| 594 |
|
| 595 |
If allowed output type is not provided, None is returned |
| 596 |
""" |
| 597 |
|
| 598 |
if self.outputtype is None: |
| 599 |
return None |
| 600 |
|
| 601 |
if outref is None: |
| 602 |
if self.outputtype == self.TEX: |
| 603 |
return ("\\bibitem%s{%s}\n Not Found!\n\n" |
| 604 |
% (biblabel if biblabel is not None else "", |
| 605 |
citekey)) |
| 606 |
if self.outputtype == self.BIBTEX: |
| 607 |
return '@MISC {%s,\n NOTE = {Not Found!}\n}\n\n' % citekey |
| 608 |
if self.outputtype == self.IMS: |
| 609 |
return ('@MISC {%s,\n HOWPUBLISHED = {%s},\n}\n\n' |
| 610 |
% (citekey, querystring)) |
| 611 |
if self.outputtype == self.AMSREFS: |
| 612 |
return ('\\bib{%s}{misc}{\n note = {Not Found!}\n}\n\n' |
| 613 |
% citekey) |
| 614 |
if self.outputtype == self.HTML: |
| 615 |
return '<!-- %s -->\nNot Found!\n<br/><br/>\n\n' % citekey |
| 616 |
return None |
| 617 |
|
| 618 |
outref = outref.strip() + '\n\n' |
| 619 |
if self.outputtype == self.TEX: |
| 620 |
return ('\\bibitem%s{%s}\n%s' |
| 621 |
% (biblabel if biblabel is not None else "", |
| 622 |
citekey, outref)) |
| 623 |
if self.outputtype in [self.BIBTEX, self.IMS]: |
| 624 |
return self.re_bibtex.sub(r'\1 {%s,' % citekey, outref) |
| 625 |
if self.outputtype == self.AMSREFS: |
| 626 |
return self.re_amsrefs.sub(r'\\bib\0{%s}{\2}' % citekey, outref) |
| 627 |
if self.outputtype == self.HTML: |
| 628 |
return '<!-- %s -->\n%s<br/><br/>\n' % (citekey, outref) |
| 629 |
return None |
| 630 |
|
| 631 |
|
| 632 |
class RefElement(object): |
| 633 |
""" This is a container for one bibliography reference item, |
| 634 |
containing all data related to it """ |
| 635 |
|
| 636 |
FORMAT_PROPERTIES = RefHandler.FORMAT_PROPERTIES |
| 637 |
|
| 638 |
def __init__(self, refid=None, reftype=None, citekey=None, biblabel=None): |
| 639 |
""" Initiate reference item container |
| 640 |
|
| 641 |
Parameters |
| 642 |
---------- |
| 643 |
refid : int or None |
| 644 |
reftype : str or None |
| 645 |
Input bibliography reference type (one of RefTypes.ITYPES). |
| 646 |
citekey : str or None |
| 647 |
Input bibliography reference cite key |
| 648 |
biblabel : str or None |
| 649 |
Input bibliography reference label, |
| 650 |
provided in the optional parameter of RefTypes.BIBITEM type |
| 651 |
reference item |
| 652 |
""" |
| 653 |
|
| 654 |
self.reftype = reftype |
| 655 |
self.refid = refid |
| 656 |
self.citekey = citekey |
| 657 |
self.biblabel = biblabel |
| 658 |
|
| 659 |
self.orig_lines = list() |
| 660 |
self.cleaned_lines = list() |
| 661 |
self.query_lines = list() |
| 662 |
self.comment_lines = list() |
| 663 |
|
| 664 |
self.errno = 0 |
| 665 |
self._init_querystring = None |
| 666 |
self._querystring = None |
| 667 |
self._mrid = None |
| 668 |
self.outref = None |
| 669 |
|
| 670 |
def normalize(self, lines): |
| 671 |
""" Normalize the reference item content |
| 672 |
Parameters |
| 673 |
---------- |
| 674 |
lines : list |
| 675 |
|
| 676 |
Returns |
| 677 |
------- |
| 678 |
str |
| 679 |
Returned string doesn't contain trailing spaces and |
| 680 |
typical ending for the reference of reftype (if found) |
| 681 |
""" |
| 682 |
nstring = re.sub('\s+', ' ', ''.join(lines)).strip() |
| 683 |
ending = self.FORMAT_PROPERTIES.get(self.reftype, |
| 684 |
dict()).get("ref_ending", "") |
| 685 |
ending_index = nstring.rfind(ending) |
| 686 |
if ending_index != -1: |
| 687 |
nstring = nstring[:ending_index].strip() |
| 688 |
return nstring |
| 689 |
|
| 690 |
@property |
| 691 |
def init_querystring(self): |
| 692 |
if self._init_querystring is not None: |
| 693 |
return self._init_querystring |
| 694 |
|
| 695 |
flog.debug(">> Normalizing the reference") |
| 696 |
self._init_querystring = self.normalize(self.query_lines) |
| 697 |
|
| 698 |
return self._init_querystring |
| 699 |
|
| 700 |
@property |
| 701 |
def querystring(self): |
| 702 |
if self._querystring is not None: |
| 703 |
return self._querystring |
| 704 |
return self.init_querystring |
| 705 |
|
| 706 |
@querystring.setter |
| 707 |
def querystring(self, istring): |
| 708 |
self._querystring = istring |
| 709 |
|
| 710 |
@property |
| 711 |
def mrid(self): |
| 712 |
return self._mrid |
| 713 |
|
| 714 |
@mrid.setter |
| 715 |
def mrid(self, mrid): |
| 716 |
""" Normalize MR number, returned by the query to BatchMRef |
| 717 |
|
| 718 |
Parameters |
| 719 |
---------- |
| 720 |
mrid : str |
| 721 |
|
| 722 |
Returns |
| 723 |
------- |
| 724 |
str |
| 725 |
If original MR number is shorter than 7 symbols, prepending 0, |
| 726 |
till it reaches 7 symbol length |
| 727 |
""" |
| 728 |
if mrid is not None: |
| 729 |
self._mrid = mrid.encode('ascii').lstrip("MR").rjust(7, '0') |
| 730 |
|
| 731 |
def __repr__(self): |
| 732 |
result = "<%s:\n" % self.__class__.__name__ |
| 733 |
for key, value in sorted(self.__dict__.items()): |
| 734 |
if key.startswith("_"): |
| 735 |
continue |
| 736 |
result += " %s = %s\n" % (key, repr(value)) |
| 737 |
result += " >\n" |
| 738 |
return result |
| 739 |
|
| 740 |
def __str__(self): |
| 741 |
return self.__repr__() |
| 742 |
|
| 743 |
|
| 744 |
class RefsContainer(object): |
| 745 |
""" This is a container holding as many bibliography reference items as |
| 746 |
is allowed by the denoted query to BatchMRef limit and data common |
| 747 |
to all of them """ |
| 748 |
|
| 749 |
def __init__(self): |
| 750 |
super(RefsContainer, self).__init__() |
| 751 |
self.elems = list() |
| 752 |
self.qerrno = 0 |
| 753 |
|
| 754 |
def append_elem(self, ref_element): |
| 755 |
""" Add bibliography reference item instance to the container |
| 756 |
|
| 757 |
Parameters |
| 758 |
---------- |
| 759 |
ref_element : RefElement() instance |
| 760 |
""" |
| 761 |
|
| 762 |
self.elems += (ref_element,) |
| 763 |
|
| 764 |
def get_elem_by_refid(self, refid): |
| 765 |
""" Get bibliography reference item instance by its id |
| 766 |
|
| 767 |
Parameters |
| 768 |
---------- |
| 769 |
refid : int |
| 770 |
|
| 771 |
Returns |
| 772 |
------- |
| 773 |
RefElement() instance or None |
| 774 |
If element with required id is not found, None is returned |
| 775 |
""" |
| 776 |
|
| 777 |
elem = [e for e in self.elems if e.refid == refid] |
| 778 |
if elem: |
| 779 |
return elem[0] |
| 780 |
|
| 781 |
def __str__(self): |
| 782 |
result = "<%s:\n" % self.__class__.__name__ |
| 783 |
for key, value in sorted(self.__dict__.items()): |
| 784 |
if key == "elems": |
| 785 |
for elem in value: |
| 786 |
result += " %s" % repr(elem) |
| 787 |
elif key not in ["elems", "qresult", "xml"]: |
| 788 |
result += " GLOBAL: {} = {}\n".format(key, value) |
| 789 |
result += " >\n" |
| 790 |
return result |
| 791 |
|
| 792 |
|
| 793 |
class QueryHandler(RefTypes): |
| 794 |
""" This class unites methods and attributes related to actions necessary |
| 795 |
for the AMS BatchMRef query """ |
| 796 |
|
| 797 |
AUTO_ENC = "auto" |
| 798 |
LATIN1 = 'latin1' |
| 799 |
ASCII = "ascii" |
| 800 |
|
| 801 |
AMS_URL = 'https://mathscinet.ams.org/batchmref' |
| 802 |
|
| 803 |
# AMS BatchMRef limit of items no per query |
| 804 |
QUERY_ITEMS_LIMIT = 100 |
| 805 |
|
| 806 |
QUERY_XML_HEADING_STRING = '<?xml version="1.0" encoding="UTF-8"?>\n' |
| 807 |
|
| 808 |
QUERY_HEADING_STRING = ( |
| 809 |
'<mref_batch>\n' |
| 810 |
' %s' |
| 811 |
'</mref_batch>' |
| 812 |
) |
| 813 |
|
| 814 |
QUERY_ITEM_STRING = ( |
| 815 |
'<mref_item outtype="%s">\n' |
| 816 |
' <inref>\n' |
| 817 |
' %s\n' |
| 818 |
' </inref>\n' |
| 819 |
' <myid>%d</myid>\n' |
| 820 |
'</mref_item>\n' |
| 821 |
) |
| 822 |
|
| 823 |
QUERY_FORMATS = { |
| 824 |
RefTypes.TEX: RefTypes.TEX, |
| 825 |
RefTypes.BIBTEX: RefTypes.BIBTEX, |
| 826 |
RefTypes.IMS: RefTypes.BIBTEX, |
| 827 |
RefTypes.AMSREFS: RefTypes.AMSREFS, |
| 828 |
RefTypes.HTML: RefTypes.HTML, |
| 829 |
None: RefTypes.TEX |
| 830 |
} |
| 831 |
|
| 832 |
PATTERN_MREF_ITEM = '(\<mref_item outtype="(?:bibtex|tex|amsrefs|html)"\>.*?\</mref_item\>)' |
| 833 |
PATTERN_BATCH_ERROR = '\<batch_error\>(.*?)\</batch_error\>' |
| 834 |
|
| 835 |
# AMS gives the following message in HTML if requested website is broken |
| 836 |
AMS_MSG = "The AMS Website is temporarily unavailable." |
| 837 |
|
| 838 |
def __init__(self, encoding, outputtype, refscontainer, address=AMS_URL): |
| 839 |
""" Initiate query to BatchMRef handling methods and attributes |
| 840 |
|
| 841 |
Parameters |
| 842 |
---------- |
| 843 |
encoding : str |
| 844 |
Input file encoding |
| 845 |
outputtype : str or None |
| 846 |
Reference output format type passed for BatchMRef query |
| 847 |
refscontainer : RefsContainer() instance |
| 848 |
address : str |
| 849 |
BatchMRef query address |
| 850 |
""" |
| 851 |
|
| 852 |
self.encoding = encoding |
| 853 |
flog.debug("Provided encoding format: %s" % encoding) |
| 854 |
self.address = address |
| 855 |
self.query_format = self.QUERY_FORMATS.get(outputtype, self.TEX) |
| 856 |
flog.debug("Query settings: URL = %s, output format = %s" |
| 857 |
% (address, self.query_format)) |
| 858 |
self.outputtype = outputtype |
| 859 |
|
| 860 |
self.errno = 0 |
| 861 |
self.qresult = None |
| 862 |
self.qcode = None |
| 863 |
self.xml = None |
| 864 |
self.re_mref_item = re.compile(self.PATTERN_MREF_ITEM, re.DOTALL) |
| 865 |
self.re_batch_error = re.compile(self.PATTERN_BATCH_ERROR, re.DOTALL) |
| 866 |
|
| 867 |
self._refscontainer = refscontainer |
| 868 |
self.query_elems = list() |
| 869 |
|
| 870 |
@property |
| 871 |
def refscontainer(self): |
| 872 |
return self._refscontainer |
| 873 |
|
| 874 |
def _encode_str(self, istring): |
| 875 |
""" Change query string encoding into the ASCII |
| 876 |
|
| 877 |
Parameters |
| 878 |
---------- |
| 879 |
istring : str |
| 880 |
|
| 881 |
Returns |
| 882 |
------- |
| 883 |
str |
| 884 |
""" |
| 885 |
|
| 886 |
str_enc = self.encoding |
| 887 |
self.errno = 0 |
| 888 |
if str_enc == self.AUTO_ENC: |
| 889 |
detector = UniversalDetector() |
| 890 |
detector.feed(istring) |
| 891 |
detector.close() |
| 892 |
str_enc = detector.result.get('encoding', self.ASCII) |
| 893 |
flog.debug(">> Determined string encoding: %s" % str_enc) |
| 894 |
|
| 895 |
if str_enc == self.ASCII: |
| 896 |
return istring |
| 897 |
if str_enc is None: |
| 898 |
flog.debug(">> Encoding determination has FAILED! ") |
| 899 |
return istring |
| 900 |
|
| 901 |
try: |
| 902 |
return istring.decode(str_enc.lower()).encode(self.ASCII, |
| 903 |
errors='replace') |
| 904 |
except: |
| 905 |
flog.debug(">> encoding given reference element FAILED!") |
| 906 |
msg = (">> encoding given reference element FAILED!\n" |
| 907 |
"[Input string]:\n%s\n" % istring) |
| 908 |
flog.exception(msg) |
| 909 |
self.errno = -2 |
| 910 |
return istring |
| 911 |
|
| 912 |
@staticmethod |
| 913 |
def _escape_tex(istring): |
| 914 |
""" Convert TeX symbols into XML valid symbols |
| 915 |
|
| 916 |
Parameters |
| 917 |
---------- |
| 918 |
istring : str |
| 919 |
|
| 920 |
Returns |
| 921 |
------- |
| 922 |
str |
| 923 |
""" |
| 924 |
|
| 925 |
flog.debug(">> Converting TeX symbols into XML valid symbols") |
| 926 |
return reduce(lambda a, b: string.replace(a, b[0], b[1]), |
| 927 |
(istring, ("\\&", '&'), ("<", '<'), (">", '>'), |
| 928 |
("&", '&'), (r"\ndash ", "-"))) |
| 929 |
|
| 930 |
def _parse_str(self, istring, check=False): |
| 931 |
""" Parse string into XML object |
| 932 |
|
| 933 |
Parameters |
| 934 |
---------- |
| 935 |
istring : str |
| 936 |
check : bool |
| 937 |
If True, checking if string parses to valid XML. |
| 938 |
If False, saving parsed XML or an error code |
| 939 |
if parsing was unsuccessful |
| 940 |
""" |
| 941 |
|
| 942 |
try: |
| 943 |
xml = parseString(istring) |
| 944 |
if not check: |
| 945 |
self.xml = xml |
| 946 |
else: |
| 947 |
flog.debug("VALIDATING XML string ...") |
| 948 |
flog.debug(">> XML contains no errors") |
| 949 |
except ExpatError as err: |
| 950 |
flog.debug(">> Parsing given XML FAILED!") |
| 951 |
msg = (">> Parsing given XML FAILED!\n", |
| 952 |
"[Parse query]:\n%s\n" % istring) |
| 953 |
flog.exception(msg) |
| 954 |
self.errno = err.code |
| 955 |
|
| 956 |
def prepare_query_str(self, refid, querystring): |
| 957 |
""" Format the reference as an XML string and validate it |
| 958 |
|
| 959 |
Parameters |
| 960 |
---------- |
| 961 |
refid : int |
| 962 |
RefElement() instance id |
| 963 |
querystring : str |
| 964 |
|
| 965 |
Returns |
| 966 |
------- |
| 967 |
int |
| 968 |
If query string was encoded and parsed into valid XML |
| 969 |
successfully, it is appended to a future query strings list |
| 970 |
and error code is set to 0 |
| 971 |
|
| 972 |
If something went wrong, non-zero value is returned |
| 973 |
""" |
| 974 |
|
| 975 |
self.errno = 0 |
| 976 |
flog.debug("PREPARING query reference") |
| 977 |
|
| 978 |
single_qstring = self._encode_str( |
| 979 |
self.QUERY_ITEM_STRING % (self.query_format, |
| 980 |
self._escape_tex(querystring), |
| 981 |
refid) |
| 982 |
) |
| 983 |
flog.debug(">> Formed query XML:\n" |
| 984 |
+ "~" * 70 + "\n%s\n" % single_qstring + "~" * 70) |
| 985 |
|
| 986 |
# Checking if formed string is a valid XML |
| 987 |
self._parse_str(single_qstring, check=True) |
| 988 |
if self.errno != 0: |
| 989 |
return self.errno |
| 990 |
|
| 991 |
self.query_elems.append(single_qstring) |
| 992 |
return self.errno |
| 993 |
|
| 994 |
def _send_query(self, querystring): |
| 995 |
""" Send query to BatchMRef |
| 996 |
|
| 997 |
Parameters |
| 998 |
---------- |
| 999 |
querystring : str |
| 1000 |
Validated XML query string, containing as many reference items |
| 1001 |
as QueryHandler.QUERY_ITEMS_LIMIT allows |
| 1002 |
|
| 1003 |
If request to BatchMRef was successful, saving query result, |
| 1004 |
otherwise non-zero error code is saved |
| 1005 |
""" |
| 1006 |
|
| 1007 |
queryinfo = {'qdata': querystring} |
| 1008 |
queryval = urllib.urlencode(queryinfo) |
| 1009 |
try: |
| 1010 |
flog.debug("SENDING query ...") |
| 1011 |
req = urllib2.Request(url=self.address, data=queryval) |
| 1012 |
flog.debug(">> Query POST data: %s" % req.get_data()) |
| 1013 |
context = ssl._create_unverified_context() |
| 1014 |
batchmref = urllib2.urlopen(req, context=context) |
| 1015 |
self.qcode = batchmref.getcode() |
| 1016 |
flog.debug(">> Query result code: %s" % self.qcode) |
| 1017 |
self.qresult = batchmref.read() |
| 1018 |
|
| 1019 |
if self.qcode == 200 and \ |
| 1020 |
self.qresult.startswith(self.QUERY_XML_HEADING_STRING): |
| 1021 |
flog.debug(">> Query result string:\n" |
| 1022 |
+ "~"*70 + "\n%s\n" % self.qresult.strip() + "~"*70) |
| 1023 |
else: |
| 1024 |
msg = "\n%s" % self.AMS_MSG if self.AMS_MSG in self.qresult else "" |
| 1025 |
flog.debug(">> Query FAILED! %s" % msg) |
| 1026 |
flog.error("Query returned an error:\n%s\n\n%s" |
| 1027 |
% (msg, self.qresult)) |
| 1028 |
self.errno = self.qcode if self.qcode != 200 else -2 |
| 1029 |
self.qresult = None |
| 1030 |
|
| 1031 |
batchmref.close() |
| 1032 |
except: |
| 1033 |
msg = ">> Query FAILED!" |
| 1034 |
flog.debug(msg) |
| 1035 |
flog.exception(msg) |
| 1036 |
self.errno = -2 |
| 1037 |
self.qresult = None |
| 1038 |
|
| 1039 |
@staticmethod |
| 1040 |
def _extract_xml_data(xml_elem, tag): |
| 1041 |
""" Extract text data from an XML object |
| 1042 |
|
| 1043 |
Parameters |
| 1044 |
---------- |
| 1045 |
xml_elem : XML object |
| 1046 |
tag : str |
| 1047 |
XML tag of interest |
| 1048 |
|
| 1049 |
Returns |
| 1050 |
------- |
| 1051 |
str or None |
| 1052 |
Content of XML element with the requested tag. |
| 1053 |
If element with the tag hasn't been found, None is returned |
| 1054 |
""" |
| 1055 |
|
| 1056 |
childelem = xml_elem.getElementsByTagName(tag) |
| 1057 |
if childelem: |
| 1058 |
childnodes = childelem[0].childNodes |
| 1059 |
if childnodes: |
| 1060 |
return childnodes[0].data |
| 1061 |
|
| 1062 |
def _analyze_xml(self, xml): |
| 1063 |
""" Extract reference data from the BatchMRef returned XML string, |
| 1064 |
parsed into XML object |
| 1065 |
|
| 1066 |
Parameters |
| 1067 |
---------- |
| 1068 |
xml : XML object |
| 1069 |
|
| 1070 |
If no matches have been found in the AMS MR DB, |
| 1071 |
current RefElement() instance gets a non-zero error code. |
| 1072 |
Otherwise MR number and reference content (if requested output type |
| 1073 |
is not None) are saved in the current RefElement() instance |
| 1074 |
""" |
| 1075 |
|
| 1076 |
mref_item = xml.getElementsByTagName("mref_item")[0] |
| 1077 |
refid = int(self._extract_xml_data(mref_item, "myid")) |
| 1078 |
elem = self.refscontainer.get_elem_by_refid(refid) |
| 1079 |
|
| 1080 |
matches = self._extract_xml_data(mref_item, "matches") |
| 1081 |
if matches == '1': |
| 1082 |
flog.debug(">> MRef DB: reference `%s' found!" % elem.citekey) |
| 1083 |
elem.mrid = self._extract_xml_data(mref_item, "mrid") |
| 1084 |
flog.debug(">> MRef ID: %s" % elem.mrid) |
| 1085 |
|
| 1086 |
if self.outputtype is not None: |
| 1087 |
elem.outref = self._extract_xml_data(mref_item, "outref") |
| 1088 |
flog.debug(">> MRef output reference:\n" |
| 1089 |
+ "~"*70 + "\n%s\n" % elem.outref.strip() + "~"*70) |
| 1090 |
else: |
| 1091 |
elem.errno = -1 |
| 1092 |
flog.debug(">> MRef DB: reference `%s' not found!" % elem.citekey) |
| 1093 |
|
| 1094 |
def query(self): |
| 1095 |
""" Send a request to AMS BatchMRef and analyze the returned data |
| 1096 |
|
| 1097 |
If query result contains 'batch_error' element or returned |
| 1098 |
XML string can't be parsed into XML object, |
| 1099 |
RefsContainer() instance gets a non-zero error code. |
| 1100 |
""" |
| 1101 |
|
| 1102 |
self.errno = 0 |
| 1103 |
self.qresult = None |
| 1104 |
|
| 1105 |
querystring = (self.QUERY_XML_HEADING_STRING |
| 1106 |
+ self.QUERY_HEADING_STRING % ("\n".join(self.query_elems))) |
| 1107 |
if self.errno == 0: |
| 1108 |
self._send_query(querystring) |
| 1109 |
if self.qresult is not None: |
| 1110 |
error_obj = self.re_batch_error.search(self.qresult) |
| 1111 |
if error_obj: |
| 1112 |
flog.debug(">> Query XML contains an ERROR!") |
| 1113 |
flog.error("[batch_error]:\n%s\n\n[querystring]:\n%s" |
| 1114 |
% (self._encode_str(error_obj.group(1)), |
| 1115 |
querystring)) |
| 1116 |
self.errno = -2 |
| 1117 |
flog.debug("Splitting query result and analyzing parts separately") |
| 1118 |
for item_qresult in self.re_mref_item.finditer(self.qresult): |
| 1119 |
self.xml = None |
| 1120 |
self._parse_str(self._encode_str(item_qresult.group())) |
| 1121 |
if self.xml is not None: |
| 1122 |
self._analyze_xml(self.xml) |
| 1123 |
|
| 1124 |
self.refscontainer.qerrno = self.errno |
| 1125 |
self.query_elems = list() |
| 1126 |
|
| 1127 |
|
| 1128 |
class HandleBBL(RefTypes): |
| 1129 |
""" This is the main class containing and initiating other classes' |
| 1130 |
methods and attributes for provided input data processing """ |
| 1131 |
|
| 1132 |
# MR number pattern matching all recognized reference formats |
| 1133 |
PATTERN_MR = r'MRNUMBER=\{.*?\}(,|)|review=\{\\MR\{.*?\}\}(,|)|\\MR\{.*?\}' |
| 1134 |
|
| 1135 |
PATTERN_BIBRE_LINE = r'^%.*\r?\n$' |
| 1136 |
PATTERN_BIBRE_PART = r'\s*(.*?)(?<!\\)%.*\r?\n$' |
| 1137 |
|
| 1138 |
PATTERN_TEX_ACCENTS = r"""(?:\{|)\\(?:"|'|`|\^|-|H|~|c|k|=|b|\.|d|r|u|v|A)(?:|\{)([a-zA-Z])\}(?:\}|)""" |
| 1139 |
PATTERN_BRACED_LETTERS = r"""(\s)(?<!\\)([a-zA-Z]*)\{([A-Z]+)\}""" |
| 1140 |
|
| 1141 |
# Mark of the input file ending |
| 1142 |
EOF = "EOF" |
| 1143 |
|
| 1144 |
# Default bibstyle format |
| 1145 |
PLAIN = 'plain' |
| 1146 |
|
| 1147 |
def __init__(self, inputfile, encoding, clean_comments, |
| 1148 |
itemno, wait, outputtype, bibstyle, debug, version=str()): |
| 1149 |
""" Initiate all methods and attributes required to process input data |
| 1150 |
|
| 1151 |
Parameters |
| 1152 |
---------- |
| 1153 |
inputfile : str or None |
| 1154 |
encoding : str |
| 1155 |
Input file encoding |
| 1156 |
clean_comments : bool |
| 1157 |
If TeX comments cleaning is selected, |
| 1158 |
full comment lines will be moved to the beginning of each |
| 1159 |
identified bibliography reference item |
| 1160 |
itemno : int |
| 1161 |
Limit of reference items per query to BatchMRef |
| 1162 |
wait: int |
| 1163 |
Pause length after each query to BatchMRef |
| 1164 |
outputtype : str or None |
| 1165 |
If not None, additional files with the requested references, |
| 1166 |
extracted from the AMS MR DB in the requested output format, |
| 1167 |
will be generated |
| 1168 |
bibstyle : str or None |
| 1169 |
Used only if the requested output type is BIBTEX or IMS |
| 1170 |
debug : int |
| 1171 |
If debug value is greater than 0, debug messages will be |
| 1172 |
written to the FileHandler.LOG file. Also, depending on the |
| 1173 |
given debug value, final data written to the input file will |
| 1174 |
contain TeX comments with query data. |
| 1175 |
version : str |
| 1176 |
""" |
| 1177 |
|
| 1178 |
self.refscontainer = RefsContainer() |
| 1179 |
|
| 1180 |
self.fh = FilesHandler(inputfile, outputtype) |
| 1181 |
self.rh = RefHandler(outputtype) |
| 1182 |
self.qh = QueryHandler(encoding, outputtype, self.refscontainer) |
| 1183 |
|
| 1184 |
if itemno < self.qh.QUERY_ITEMS_LIMIT: |
| 1185 |
self.qh.QUERY_ITEMS_LIMIT = itemno |
| 1186 |
self.wait = wait |
| 1187 |
|
| 1188 |
self.outputtype = outputtype |
| 1189 |
self.bibstyle = bibstyle |
| 1190 |
flog.debug("Comments will be cleaned from the output: %s" |
| 1191 |
% clean_comments) |
| 1192 |
self.clean_comments = clean_comments |
| 1193 |
self.debug = debug |
| 1194 |
self.version = version |
| 1195 |
|
| 1196 |
self.re_bibre_line = re.compile(self.PATTERN_BIBRE_LINE) |
| 1197 |
self.re_bibre_part = re.compile(self.PATTERN_BIBRE_PART) |
| 1198 |
self.re_MR = re.compile(self.PATTERN_MR) |
| 1199 |
self.re_tex_accents = re.compile(self.PATTERN_TEX_ACCENTS) |
| 1200 |
self.re_braced_letters = re.compile(self.PATTERN_BRACED_LETTERS) |
| 1201 |
|
| 1202 |
self.eof = False |
| 1203 |
self.ifile_end_lines = list() |
| 1204 |
|
| 1205 |
@property |
| 1206 |
def icontent(self): |
| 1207 |
""" Input file content """ |
| 1208 |
return self.fh.read(self.fh.IN) |
| 1209 |
|
| 1210 |
@property |
| 1211 |
def write(self): |
| 1212 |
return self.fh.write |
| 1213 |
|
| 1214 |
@property |
| 1215 |
def get_fname(self): |
| 1216 |
return self.fh.get_fname |
| 1217 |
|
| 1218 |
def preprocess_ofiles(self): |
| 1219 |
""" Depending on the requested bibliography output type, |
| 1220 |
certain files are pre-filled with required data. |
| 1221 |
Writing action is fulfilled only if requested file was pre-opened. |
| 1222 |
""" |
| 1223 |
self.write(self.fh.AUX, '\\bibstyle{%s}\n' % self.bibstyle) |
| 1224 |
self.write(self.fh.HTML, "<!DOCTYPE html>\n<html>\n<body>\n\n") |
| 1225 |
|
| 1226 |
def postprocess_ofiles(self, refcount): |
| 1227 |
""" Depending on the requested bibliography output type, |
| 1228 |
certain files are filled up with the required data. |
| 1229 |
Writing action is fulfilled only if requested file was pre-opened. |
| 1230 |
|
| 1231 |
Parameters |
| 1232 |
---------- |
| 1233 |
refcount: int |
| 1234 |
If refcount is 0, it means no references have been found |
| 1235 |
in the input file, and pre-opened additional files are deleted |
| 1236 |
|
| 1237 |
If requested bibliography output type is TEX, |
| 1238 |
number of bibliography items found is written to the first line of |
| 1239 |
FileHandler.DATA file. Therefore this file is written twice into. |
| 1240 |
""" |
| 1241 |
|
| 1242 |
if refcount == 0: |
| 1243 |
self.fh.close_and_delete(self.fh.DATA) |
| 1244 |
self.fh.close_and_delete(self.fh.AUX) |
| 1245 |
return None |
| 1246 |
|
| 1247 |
datafilepath = self.get_fname(self.fh.DATA) |
| 1248 |
self.write(self.fh.AUX, |
| 1249 |
'\\bibdata{%s}' % os.path.splitext(datafilepath)[0]) |
| 1250 |
self.write(self.fh.HTML, "\n</body>\n</html>\n") |
| 1251 |
|
| 1252 |
# Formatting the DATA file output according to requested output format |
| 1253 |
obiblenv = { |
| 1254 |
self.TEX: { |
| 1255 |
"begin": "\\begin{thebibliography}{%s}\n" |
| 1256 |
"\\csname bibmessage\\endcsname\n\n", |
| 1257 |
"end": "\\end{thebibliography}\n" |
| 1258 |
}, |
| 1259 |
self.AMSREFS: { |
| 1260 |
"begin": "\\begin{bibdiv}\n\\begin{biblist}\n\n", |
| 1261 |
"end": "\\end{biblist}\n\\end{bibdiv}" |
| 1262 |
} |
| 1263 |
} |
| 1264 |
|
| 1265 |
strings = obiblenv.get(self.outputtype, None) |
| 1266 |
if strings is None: |
| 1267 |
return None |
| 1268 |
|
| 1269 |
start_string, finish_string = sorted(strings.values()) |
| 1270 |
self.write(self.fh.DATA, finish_string) |
| 1271 |
|
| 1272 |
# Total items count is known only after processing all references and |
| 1273 |
# writing to the DATA file, therefore 'thebibliography' environment |
| 1274 |
# starting string is written to this file when all processing is |
| 1275 |
# finished |
| 1276 |
self.fh.close(self.fh.DATA) |
| 1277 |
os.rename(datafilepath, self.get_fname(self.fh.TMP)) |
| 1278 |
self.fh.open(self.fh.TMP, self.fh.READ) |
| 1279 |
|
| 1280 |
if self.outputtype == self.TEX: |
| 1281 |
start_string = start_string % refcount |
| 1282 |
self.fh.open(self.fh.DATA, self.fh.WRITE) |
| 1283 |
self.write(self.fh.DATA, start_string) |
| 1284 |
|
| 1285 |
shutil.copyfileobj(self.fh.files[self.fh.TMP], |
| 1286 |
self.fh.files[self.fh.DATA]) |
| 1287 |
|
| 1288 |
def _remove_tex_comments(self, line): |
| 1289 |
""" Remove TeX comments |
| 1290 |
|
| 1291 |
Parameters |
| 1292 |
---------- |
| 1293 |
line : str |
| 1294 |
|
| 1295 |
Returns |
| 1296 |
------- |
| 1297 |
str |
| 1298 |
""" |
| 1299 |
fmtline = self.re_bibre_line.sub('', line) |
| 1300 |
if fmtline: |
| 1301 |
matchobj = self.re_bibre_part.search(fmtline) |
| 1302 |
if matchobj is not None: |
| 1303 |
return "%s\n" % matchobj.groups(1)[0] |
| 1304 |
return fmtline |
| 1305 |
return fmtline |
| 1306 |
|
| 1307 |
def _remove_tex_accents(self, line): |
| 1308 |
""" Remove TeX accents and braces around upper case letters |
| 1309 |
|
| 1310 |
BatchMRef may not found a reference in the AMS MR DB because of |
| 1311 |
braces and accents present in reference string (tested), therefore |
| 1312 |
accented letters "{\'a}" and "\'{a}" are changed to plain "a". |
| 1313 |
Also "{ABC}" is changed to "ABC". |
| 1314 |
|
| 1315 |
Parameters |
| 1316 |
---------- |
| 1317 |
line : str |
| 1318 |
|
| 1319 |
Returns |
| 1320 |
------- |
| 1321 |
str |
| 1322 |
""" |
| 1323 |
mline = self.re_tex_accents.sub(r'\1', line) |
| 1324 |
if mline: |
| 1325 |
return self.re_braced_letters.sub(r'\1\2\3', mline) |
| 1326 |
return mline |
| 1327 |
|
| 1328 |
def gather_records(self, require_env): |
| 1329 |
""" Extract bibliography reference items from the input file |
| 1330 |
|
| 1331 |
Parameters |
| 1332 |
---------- |
| 1333 |
require_env : bool |
| 1334 |
If True, get bibliography reference items only inside |
| 1335 |
the bibliography environment. If False, gel all bibliography |
| 1336 |
reference items found in the input file |
| 1337 |
|
| 1338 |
Yields |
| 1339 |
------- |
| 1340 |
str |
| 1341 |
Denotes reference format type (one of ITYPES), |
| 1342 |
bibliography environment state (RefHandler.BIBL_BEGIN or |
| 1343 |
RefHandler.BIBL_END), |
| 1344 |
or input file end mark (EOF) |
| 1345 |
|
| 1346 |
RefElement() instance, str, or None |
| 1347 |
If reference of one of ITYPES type has been found, |
| 1348 |
a RefElement() instance is returned with the following |
| 1349 |
attributes filled in: |
| 1350 |
reftype, citekey, biblabel, |
| 1351 |
orig_lines, cleaned_lines, query_lines |
| 1352 |
|
| 1353 |
If end of input file has been determined, None is returned |
| 1354 |
|
| 1355 |
Otherwise current line is returned |
| 1356 |
""" |
| 1357 |
|
| 1358 |
def sort_comments_out(comment_lines): |
| 1359 |
""" Assign gathered comment lines to the rightful reference item |
| 1360 |
|
| 1361 |
Parameters |
| 1362 |
---------- |
| 1363 |
comment_lines : list |
| 1364 |
|
| 1365 |
Returns |
| 1366 |
------- |
| 1367 |
list |
| 1368 |
Comment lines, belonging to current reference item |
| 1369 |
list |
| 1370 |
Comment lines, belonging to the next reference item |
| 1371 |
""" |
| 1372 |
|
| 1373 |
next_elem_comments = [] |
| 1374 |
reversed_comments = comment_lines[::-1] |
| 1375 |
reversed_comments_backup = comment_lines[::-1] |
| 1376 |
advanced_by = 0 |
| 1377 |
for no, cline in enumerate(reversed_comments): |
| 1378 |
if len(element.orig_lines) < (no + 1 + advanced_by): |
| 1379 |
break |
| 1380 |
while not element.orig_lines[-(no + 1 + advanced_by)].strip(): |
| 1381 |
# skipping empty lines |
| 1382 |
advanced_by += 1 |
| 1383 |
if cline == element.orig_lines[-(no + 1 + advanced_by)]: |
| 1384 |
reversed_comments_backup.pop(0) |
| 1385 |
next_elem_comments.append(reversed_comments[no]) |
| 1386 |
current_elem_comments = reversed_comments_backup[::-1] |
| 1387 |
return current_elem_comments, next_elem_comments |
| 1388 |
|
| 1389 |
# Allowing gathering the references according to |
| 1390 |
# the bibliography environment status |
| 1391 |
envmap = {self.rh.BIBL_BEGIN: True, |
| 1392 |
self.rh.BIBL_END: False, |
| 1393 |
"not found": False if require_env else True} |
| 1394 |
gather = envmap["not found"] |
| 1395 |
search = True |
| 1396 |
|
| 1397 |
multiline = "" |
| 1398 |
element = RefElement() |
| 1399 |
envstatus = None |
| 1400 |
for line in self.icontent: |
| 1401 |
line = multiline + line |
| 1402 |
clean_line = self._remove_tex_comments(line) |
| 1403 |
|
| 1404 |
if not clean_line and element.orig_lines: |
| 1405 |
element.orig_lines.append(line) |
| 1406 |
element.comment_lines.append(line) |
| 1407 |
continue |
| 1408 |
|
| 1409 |
reftype = None |
| 1410 |
if search: |
| 1411 |
reftype, additional_info = self.rh.find_reference(clean_line) |
| 1412 |
|
| 1413 |
if require_env and reftype == self.rh.BIBL_ENV: |
| 1414 |
if element.reftype is not None: |
| 1415 |
# Full bibliography item |
| 1416 |
element.comment_lines, next_elem_comments = \ |
| 1417 |
sort_comments_out(element.comment_lines) |
| 1418 |
yield element.reftype, element |
| 1419 |
element = RefElement() |
| 1420 |
element.comment_lines = next_elem_comments |
| 1421 |
|
| 1422 |
# Bibliography environment |
| 1423 |
envstatus = additional_info.pop("envstatus", None) |
| 1424 |
if envstatus in envmap: |
| 1425 |
gather = envmap[envstatus] |
| 1426 |
search = gather |
| 1427 |
yield envstatus, line |
| 1428 |
continue |
| 1429 |
|
| 1430 |
elif reftype in self.ITYPES: |
| 1431 |
multiline = additional_info.get("line", "") |
| 1432 |
if multiline: |
| 1433 |
continue |
| 1434 |
|
| 1435 |
if element.reftype is not None: |
| 1436 |
# Full bibliography item |
| 1437 |
element.comment_lines, next_elem_comments = \ |
| 1438 |
sort_comments_out(element.comment_lines) |
| 1439 |
yield element.reftype, element |
| 1440 |
element = RefElement() |
| 1441 |
element.comment_lines = next_elem_comments |
| 1442 |
|
| 1443 |
if gather: |
| 1444 |
element.reftype = reftype |
| 1445 |
element.citekey = additional_info.get("citekey", None) |
| 1446 |
element.biblabel = additional_info.get("biblabel", None) |
| 1447 |
element.orig_lines.append(line) |
| 1448 |
|
| 1449 |
mrid_free_line = self.re_MR.sub('', clean_line) |
| 1450 |
element.cleaned_lines.append(mrid_free_line) |
| 1451 |
|
| 1452 |
ref_format_free_line = additional_info.get("text", clean_line) |
| 1453 |
mrid_free_line = self.re_MR.sub('', ref_format_free_line) |
| 1454 |
accent_free_line = self._remove_tex_accents(mrid_free_line) |
| 1455 |
element.query_lines.append(accent_free_line) |
| 1456 |
continue |
| 1457 |
|
| 1458 |
if gather and element.reftype is not None: |
| 1459 |
element.orig_lines.append(line) |
| 1460 |
mrid_free_line = self.re_MR.sub('', clean_line) |
| 1461 |
element.cleaned_lines.append(mrid_free_line) |
| 1462 |
accent_free_line = self._remove_tex_accents(mrid_free_line) |
| 1463 |
element.query_lines.append(accent_free_line) |
| 1464 |
else: |
| 1465 |
# Before and after the bibliography environment |
| 1466 |
yield envstatus, line |
| 1467 |
|
| 1468 |
if element.reftype is not None: |
| 1469 |
# The last full bibliography item |
| 1470 |
element.comment_lines, _ = sort_comments_out(element.comment_lines) |
| 1471 |
yield element.reftype, element |
| 1472 |
|
| 1473 |
yield self.EOF, None |
| 1474 |
|
| 1475 |
def transfer_to_file(self): |
| 1476 |
""" After each query to BatchMRef write gathered data into files |
| 1477 |
|
| 1478 |
Returns |
| 1479 |
------- |
| 1480 |
int |
| 1481 |
Number of references, for which data has been successfully |
| 1482 |
obtained |
| 1483 |
""" |
| 1484 |
|
| 1485 |
successful = 0 |
| 1486 |
|
| 1487 |
for elem in self.refscontainer.elems: |
| 1488 |
if self.refscontainer.qerrno != 0: |
| 1489 |
elem.errno = self.refscontainer.qerrno |
| 1490 |
outstring = ''.join(elem.cleaned_lines if self.clean_comments else |
| 1491 |
elem.orig_lines) |
| 1492 |
|
| 1493 |
elem.outref = self.rh.insert_citekey( |
| 1494 |
elem.outref, elem.citekey, elem.biblabel, |
| 1495 |
elem.normalize(elem.cleaned_lines[1:])) |
| 1496 |
if elem.mrid is not None: |
| 1497 |
outstring = self.rh.insert_mrid(elem.reftype, outstring, elem.mrid) |
| 1498 |
slog.info(elem.mrid) |
| 1499 |
elif elem.errno == -1: |
| 1500 |
slog.warn('NotFound') |
| 1501 |
else: |
| 1502 |
slog.error('QueryError') |
| 1503 |
|
| 1504 |
if self.clean_comments: |
| 1505 |
outstring = "".join(elem.comment_lines) + outstring |
| 1506 |
|
| 1507 |
if self.debug == 1: |
| 1508 |
outstring = '%%%% %s\n%s' % (elem.querystring, outstring) |
| 1509 |
elif self.debug == 2: |
| 1510 |
outstring = '%%%% %s\n%s' % (elem.errno, outstring) |
| 1511 |
elif self.debug == 3: |
| 1512 |
outstring = '%%%% %s\n%%%% %s\n%s' % (elem.querystring, |
| 1513 |
elem.errno, |
| 1514 |
outstring) |
| 1515 |
|
| 1516 |
flog.debug("\n" + ">" * 70 |
| 1517 |
+ "\nFINAL reference with MR id in original format:\n" |
| 1518 |
+ "\n%s\n" % outstring.strip()) |
| 1519 |
|
| 1520 |
if elem.outref is not None: |
| 1521 |
flog.debug("FINAL reference in '%s' format:\n" % self.outputtype |
| 1522 |
+ "\n%s\n" % elem.outref.strip() + "<" * 70) |
| 1523 |
self.write(self.fh.OUT, outstring) |
| 1524 |
self.write(self.fh.DATA, elem.outref if elem.outref else "") |
| 1525 |
self.write(self.fh.AUX, '\\citation{%s}\n' % elem.citekey) |
| 1526 |
|
| 1527 |
if elem.errno == 0 and self.refscontainer.qerrno == 0: |
| 1528 |
successful += 1 |
| 1529 |
|
| 1530 |
if self.eof: |
| 1531 |
while self.ifile_end_lines: |
| 1532 |
self.write(self.fh.OUT, self.ifile_end_lines.pop(0)) |
| 1533 |
|
| 1534 |
self.refscontainer = RefsContainer() |
| 1535 |
self.qh._refscontainer = self.refscontainer |
| 1536 |
|
| 1537 |
return successful |
| 1538 |
|
| 1539 |
def get_mr_codes(self, require_env): |
| 1540 |
""" Analyze input file content and process found reference items |
| 1541 |
|
| 1542 |
Parameters |
| 1543 |
---------- |
| 1544 |
require_env : bool |
| 1545 |
If True, and if no bibliography reference items have been found |
| 1546 |
inside the bibliography environment, or an environment hasn't |
| 1547 |
been found at all, parameter is set to False this method and |
| 1548 |
reruns itself in order to search reference items in |
| 1549 |
the whole input file. |
| 1550 |
|
| 1551 |
Returns |
| 1552 |
------- |
| 1553 |
int |
| 1554 |
Total bibliography reference items found |
| 1555 |
int |
| 1556 |
Total number of references, for which data has been |
| 1557 |
successfully obtained |
| 1558 |
int |
| 1559 |
Reference items processed with errors count |
| 1560 |
|
| 1561 |
If reference item of ITYPES has been found, current |
| 1562 |
RefElement() instance attribute 'refid' is assigned a value |
| 1563 |
""" |
| 1564 |
|
| 1565 |
msg = ("in the bibliography environment only" |
| 1566 |
if require_env else "in the whole input file") |
| 1567 |
flog.debug("SEARCHING for reference items: %s" % msg) |
| 1568 |
|
| 1569 |
total = 0 |
| 1570 |
valid = 0 |
| 1571 |
successful = 0 |
| 1572 |
records = self.gather_records(require_env=require_env) |
| 1573 |
pseudo_citekey = 0 |
| 1574 |
for reftype, record in records: |
| 1575 |
if reftype == self.EOF: |
| 1576 |
self.eof = True |
| 1577 |
|
| 1578 |
elif reftype not in self.ITYPES: |
| 1579 |
if reftype != self.rh.BIBL_END: |
| 1580 |
self.write(self.fh.OUT, record) |
| 1581 |
else: |
| 1582 |
self.ifile_end_lines.append(record) |
| 1583 |
continue |
| 1584 |
|
| 1585 |
elif valid == 0 or valid % self.qh.QUERY_ITEMS_LIMIT != 0: |
| 1586 |
total += 1 |
| 1587 |
|
| 1588 |
record.refid = total |
| 1589 |
if not record.citekey: |
| 1590 |
pseudo_citekey += 1 |
| 1591 |
record.citekey = '%s' % pseudo_citekey |
| 1592 |
|
| 1593 |
flog.debug("=" * 70) |
| 1594 |
flog.debug("FOUND reference %s: type=%s, cite_key=%s, biblabel=%s" |
| 1595 |
% (total, reftype, record.citekey, record.biblabel)) |
| 1596 |
|
| 1597 |
if reftype != self.BIBITEM: |
| 1598 |
record.querystring = self.rh.extract_keys_data(record.query_lines) |
| 1599 |
self.refscontainer.append_elem(record) |
| 1600 |
record.errno = self.qh.prepare_query_str(record.refid, |
| 1601 |
record.querystring) |
| 1602 |
if record.errno == 0: |
| 1603 |
valid += 1 |
| 1604 |
|
| 1605 |
if valid != 0 and (valid % self.qh.QUERY_ITEMS_LIMIT == 0 |
| 1606 |
or self.eof): |
| 1607 |
self.qh.query() |
| 1608 |
successful += self.transfer_to_file() |
| 1609 |
valid = 0 |
| 1610 |
if not self.eof: |
| 1611 |
sleep(self.wait) |
| 1612 |
|
| 1613 |
if total == 0 and require_env: |
| 1614 |
# If no bibliography items were found in the bibliography |
| 1615 |
# environment, then trying to search for them everywhere |
| 1616 |
# in the input file |
| 1617 |
flog.debug("FOUND no references! Changing the search mode ... ") |
| 1618 |
self.eof = False |
| 1619 |
self.ifile_end_lines = list() |
| 1620 |
self.fh.close(self.fh.OUT) |
| 1621 |
self.fh.open(self.fh.OUT) |
| 1622 |
return self.get_mr_codes(require_env=False) |
| 1623 |
|
| 1624 |
if self.ifile_end_lines: |
| 1625 |
self.transfer_to_file() |
| 1626 |
|
| 1627 |
flog.debug("=" * 70) |
| 1628 |
errors = total - successful |
| 1629 |
return total, successful, errors |
| 1630 |
|
| 1631 |
def run(self, require_env): |
| 1632 |
""" Main method |
| 1633 |
|
| 1634 |
Parameters |
| 1635 |
---------- |
| 1636 |
require_env : bool |
| 1637 |
|
| 1638 |
Returns |
| 1639 |
------- |
| 1640 |
get_mr_codes() output |
| 1641 |
""" |
| 1642 |
|
| 1643 |
slog.info("# %s #\nJob started:" % self.version) |
| 1644 |
starttime = time() |
| 1645 |
|
| 1646 |
self.preprocess_ofiles() |
| 1647 |
total, successful, errors = self.get_mr_codes(require_env=require_env) |
| 1648 |
self.postprocess_ofiles(refcount=total) |
| 1649 |
|
| 1650 |
flog.info(" total: %s, found: %s, not found: %s, time: %ss" |
| 1651 |
% (total, successful, errors, int(round(time()-starttime)))) |
| 1652 |
|
| 1653 |
slog.info("Job ended") |
| 1654 |
slog.info("Total: %s, found: %s, not found: %s" |
| 1655 |
% (total, successful, errors)) |
| 1656 |
slog.info('Job completed in %ss' % int(round(time()-starttime))) |
| 1657 |
|
| 1658 |
self.fh.close_files() |
| 1659 |
return total, successful, errors |
| 1660 |
|
| 1661 |
|
| 1662 |
if __name__ == '__main__': |
| 1663 |
import argparse |
| 1664 |
|
| 1665 |
# Logging to console |
| 1666 |
osh = logging.StreamHandler(stream=sys.stdout) |
| 1667 |
osh.setFormatter(BASICFORMATTER) |
| 1668 |
osh.setLevel(logging.INFO) |
| 1669 |
osh.addFilter(LessThanFilter(logging.INFO)) |
| 1670 |
|
| 1671 |
esh = logging.StreamHandler(stream=sys.stderr) |
| 1672 |
esh.setFormatter(BASICFORMATTER) |
| 1673 |
esh.setLevel(logging.WARN) |
| 1674 |
|
| 1675 |
slog = logging.getLogger("%s.StreamLogger" % __name__) |
| 1676 |
slog.setLevel(logging.INFO) |
| 1677 |
slog.addHandler(osh) |
| 1678 |
slog.addHandler(esh) |
| 1679 |
|
| 1680 |
# Logging to files |
| 1681 |
flog = logging.getLogger("%s.FileLogger" % __name__) |
| 1682 |
flog.setLevel(logging.DEBUG) |
| 1683 |
|
| 1684 |
def setup_logging_files(debug, basename=""): |
| 1685 |
""" Set up logging files |
| 1686 |
|
| 1687 |
Parameters |
| 1688 |
---------- |
| 1689 |
debug : int |
| 1690 |
basename: str |
| 1691 |
Input file name |
| 1692 |
|
| 1693 |
Returns |
| 1694 |
------- |
| 1695 |
logging instance |
| 1696 |
""" |
| 1697 |
|
| 1698 |
if debug == 0: |
| 1699 |
log_min_level = logging.INFO |
| 1700 |
log_max_level = logging.INFO |
| 1701 |
formatter = BASICFORMATTER |
| 1702 |
else: |
| 1703 |
log_min_level = logging.DEBUG |
| 1704 |
log_max_level = logging.WARN |
| 1705 |
formatter = DEBUGFORMATTER |
| 1706 |
|
| 1707 |
ofh = logging.FileHandler(filename="{}.{}.{}".format(basename, |
| 1708 |
FilesHandler.GMR_SUFFIX, |
| 1709 |
FilesHandler.LOG), |
| 1710 |
mode='w', delay=True) |
| 1711 |
ofh.setFormatter(formatter) |
| 1712 |
ofh.setLevel(log_min_level) |
| 1713 |
ofh.addFilter(LessThanFilter(log_max_level)) |
| 1714 |
flog.addHandler(ofh) |
| 1715 |
|
| 1716 |
efh = logging.FileHandler(filename="{}.{}.{}".format(basename, |
| 1717 |
FilesHandler.GMR_SUFFIX, |
| 1718 |
FilesHandler.ERR), |
| 1719 |
mode='w', delay=True) |
| 1720 |
efh.setFormatter(DEBUGFORMATTER) |
| 1721 |
efh.setLevel(logging.ERROR) |
| 1722 |
flog.addHandler(efh) |
| 1723 |
return flog |
| 1724 |
|
| 1725 |
VERSION = __version__.split("-")[0] |
| 1726 |
DESCRIPTION = ( |
| 1727 |
"Tool %s, is designed for: " % VERSION |
| 1728 |
+ "(1) getting MR numbers for given references from AMS MRef database, " |
| 1729 |
+ "(2) formatting the given references in one of AMS allowed formats. " |
| 1730 |
+ "Maintainer: L.Tolene <[email protected]>." |
| 1731 |
) |
| 1732 |
|
| 1733 |
def get_cmd_args(): |
| 1734 |
""" Command line input parser """ |
| 1735 |
|
| 1736 |
parser = argparse.ArgumentParser( |
| 1737 |
description=DESCRIPTION, |
| 1738 |
formatter_class=argparse.ArgumentDefaultsHelpFormatter |
| 1739 |
) |
| 1740 |
parser.add_argument("filepath", help="References containing file") |
| 1741 |
parser.add_argument( |
| 1742 |
"--enc", '-e', type=str, default=QueryHandler.LATIN1, |
| 1743 |
help="Source file encoding or 'auto'" |
| 1744 |
) |
| 1745 |
parser.add_argument( |
| 1746 |
"--format", '-f', choices=set(RefTypes.OTYPES), |
| 1747 |
help="Outputs the given references in provided format. " |
| 1748 |
"For more information about these formats please " |
| 1749 |
"consult the AMS MRef tool website. The 'ims' format " |
| 1750 |
"is almost the same as the 'bibtex' format" |
| 1751 |
) |
| 1752 |
parser.add_argument( |
| 1753 |
"--bibstyle", '-s', default=HandleBBL.PLAIN, |
| 1754 |
help="BibTeX style. For more information please consult " |
| 1755 |
"the BibTeX documentation" |
| 1756 |
) |
| 1757 |
parser.add_argument( |
| 1758 |
"--nobibenv", action='store_true', |
| 1759 |
help="If activated, references are searched throughout " |
| 1760 |
"all source file content; otherwise searching only " |
| 1761 |
"inside the bibliography environment. Currently " |
| 1762 |
"recognizable are the 'thebibliography' and 'biblist' " |
| 1763 |
"environments" |
| 1764 |
) |
| 1765 |
parser.add_argument( |
| 1766 |
"--clean", '-c', action='store_true', |
| 1767 |
help="If activated, cleans comments appearing in references" |
| 1768 |
) |
| 1769 |
parser.add_argument( |
| 1770 |
"--itemno", default=100, type=int, |
| 1771 |
help="Maximum item count for one AMS query. " |
| 1772 |
"AMS batchmref has a limit of 100 items per query." |
| 1773 |
) |
| 1774 |
parser.add_argument( |
| 1775 |
"--wait", default=10, type=int, |
| 1776 |
help="time (in seconds) to wait between queries to AMS batchmref." |
| 1777 |
) |
| 1778 |
parser.add_argument( |
| 1779 |
"--debug", '-d', choices={0, 1, 2, 3}, default=0, type=int, |
| 1780 |
help="Outputs additional info for debugging purposes." |
| 1781 |
) |
| 1782 |
parser.add_argument( |
| 1783 |
"--version", '-v', action='version', version=VERSION, |
| 1784 |
help="Module version." |
| 1785 |
) |
| 1786 |
args = parser.parse_args() |
| 1787 |
return (args.filepath, args.enc, args.format, args.bibstyle, |
| 1788 |
args.nobibenv, args.clean, args.itemno, args.wait, args.debug) |
| 1789 |
|
| 1790 |
# Get input parameter values |
| 1791 |
inputfile, encoding, output_format, bibstyle, nobibenv, clean, itemno, wait, debug \ |
| 1792 |
= get_cmd_args() |
| 1793 |
|
| 1794 |
# Load additional library is needed |
| 1795 |
if encoding == QueryHandler.AUTO_ENC: |
| 1796 |
from chardet.universaldetector import UniversalDetector |
| 1797 |
|
| 1798 |
# Setup logging files |
| 1799 |
flog = setup_logging_files(debug=debug, |
| 1800 |
basename=os.path.splitext(inputfile)[0]) |
| 1801 |
|
| 1802 |
# Create HandleBBL() instance |
| 1803 |
bblobj = HandleBBL(inputfile=inputfile, encoding=encoding, |
| 1804 |
clean_comments=clean, itemno=itemno, wait=wait, |
| 1805 |
outputtype=output_format, bibstyle=bibstyle, |
| 1806 |
debug=debug, version=VERSION) |
| 1807 |
|
| 1808 |
# Process input file |
| 1809 |
bblobj.run(require_env=not nobibenv) |