#!/usr/bin/env python3
"""Job #1507 channel probe (read-only, no credentials).
Purpose: fill the one channel job #1500 / return #705 recorded as *unfilled* --
MathSciNet's free `mrlookup` endpoint, whose recipe is in
research/SEARCH-CONVENTIONS.md section 5 -- and re-run the zbMATH channel as a
calibration in the same process, so a zero is a channel negative and not a
broken channel.
Every raw reply is written to work/job1507-searches/ and hashed. Nothing is
interpreted here; the report does the reading.
"""
import hashlib
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, 'job1507-searches')
os.makedirs(OUT, exist_ok=True)
UA = 'solveathome-prior-art/1.0 (research; contact: department agent)'
SAVED = []
def sha256(b):
return hashlib.sha256(b).hexdigest()
def save(name, body, status, url, extra=None):
path = os.path.join(OUT, name)
with open(path, 'wb') as f:
f.write(body)
rec = {'file': name, 'url': url, 'status': status, 'bytes': len(body),
'sha256': sha256(body)}
if extra:
rec.update(extra)
SAVED.append(rec)
return rec
def fetch(url, data=None, headers=None, tries=2, timeout=45):
last = None
hdrs = {'User-Agent': UA}
if headers:
hdrs.update(headers)
for _ in range(tries):
try:
req = urllib.request.Request(url, data=data, headers=hdrs)
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
except Exception as e:
last = repr(e)
time.sleep(3)
return None, last.encode()
# ---------------------------------------------------------------- MathSciNet
# SEARCH-CONVENTIONS.md section 5: `POST https://mathscinet.ams.org/mrlookup`
# with fields au, ti, jrnl, year, format=bibtex is free; bibliographic only
# (no reviews, no abstracts, no MSC).
MRL = [
# calibration: a known positive of this project (Motohashi 1976).
('CAL MR au=Motohashi year=1976',
{'au': 'Motohashi', 'year': '1976', 'format': 'bibtex'}),
# the target: Levin 1984 (Zbl 0547.10037).
('MR au=Levin ti=distribution year=1984',
{'au': 'Levin', 'ti': 'distribution', 'year': '1984', 'format': 'bibtex'}),
('MR au=Levin ti=Bombieri year=1980',
{'au': 'Levin', 'ti': 'Bombieri', 'year': '1980', 'format': 'bibtex'}),
('MR ti=average distribution progressions year=1984',
{'ti': 'average distribution', 'jrnl': '', 'year': '1984', 'format': 'bibtex'}),
]
def mrlookup():
for label, fields in MRL:
data = urllib.parse.urlencode(fields).encode()
url = 'https://mathscinet.ams.org/mrlookup'
status, body = fetch(url, data=data,
headers={'Content-Type':
'application/x-www-form-urlencoded'})
name = 'mrlookup-%02d.txt' % (len([s for s in SAVED
if s['file'].startswith('mrlookup')]) + 1)
text = body.decode('utf-8', 'replace') if body else ''
rec = save(name, body, status, url, {'label': label, 'fields': fields})
n = re.search(r'(?i)(\d+)\s*(?:records?|matches|results?)', text)
print('%-46s status=%s bytes=%d sha=%s match_count=%s'
% (label[:46], status, rec['bytes'], rec['sha256'][:12],
n.group(1) if n else '?'))
for m in re.findall(r'(?m)^\s*(?:title|author|journal|year|@\w+)\s*=\s*(.{0,110})', text)[:8]:
print(' | ' + re.sub(r'\s+', ' ', m)[:110])
if not text.strip():
print(' | EMPTY BODY')
else:
snip = re.sub(r'\s+', ' ', re.sub(r'<[^>]+>', ' ', text))
print(' > ' + snip[:300])
time.sleep(2)
# ------------------------------------------------------------------- zbMATH
ZBM = [
('CAL zbmath: Jacobsthal function', 'Jacobsthal function'),
('zbmath: Levin average distribution arithmetic progressions',
'Levin average distribution arithmetic progressions'),
]
def zbmath():
for label, q in ZBM:
url = ('https://api.zbmath.org/v1/document/_search?search_string='
+ urllib.parse.quote(q) + '&results_per_page=20&page=0')
status, body = fetch(url)
name = 'zbmath-%02d.json' % (len([s for s in SAVED
if s['file'].startswith('zbmath')]) + 1)
hits = []
if status == 200:
try:
d = json.loads(body.decode('utf-8', 'replace'))
for r in (d.get('result') or [])[:20]:
t = r.get('title')
t = t.get('title') if isinstance(t, dict) else t
hits.append({'title': t, 'year': r.get('year'),
'id': r.get('identifier'),
'zbmath_url': r.get('zbmath_url'),
'source': r.get('source'),
'links': r.get('links'),
'msc': [m.get('code') for m in (r.get('msc') or [])],
'has_review': bool(r.get('review'))})
except Exception as e:
hits = [{'parse_error': repr(e)}]
save(name, body, status, url, {'label': label, 'query': q, 'results': hits})
print('%-46s status=%s hits=%d sha=%s' % (label[:46], status, len(hits),
sha256(body)[:12]))
for h in hits[:8]:
print(' - %s (%s) id=%s review=%s'
% (str(h.get('title'))[:80], h.get('year'), h.get('id'),
h.get('has_review')))
time.sleep(1.5)
# -------------------------------------------------------------------- arXiv
ARX = [
('CAL arxiv: ti:"Jacobsthal function"', 'ti:"Jacobsthal function"'),
('arxiv: all:"Levin" AND all:"Bombieri-Vinogradov"',
'all:"Levin" AND all:"Bombieri-Vinogradov"'),
]
def arxiv():
for label, q in ARX:
url = ('http://export.arxiv.org/api/query?search_query='
+ urllib.parse.quote(q) + '&start=0&max_results=20&sortBy=relevance')
status, body = fetch(url)
name = 'arxiv-%02d.xml' % (len([s for s in SAVED
if s['file'].startswith('arxiv')]) + 1)
ts = []
if status == 200:
for e in re.findall(r'