rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
public_scan = (e_public_scan and epublic_scan.text == 'true') or (e_ia is not None), overdrive = (e_overdrive.text.split(';') if e_overdrive else []), lending_edition = (e_lending_edition.text if e_lending_edition else None),
public_scan = ((e_public_scan.text == 'true') if e_public_scan is not None else (e_ia is not None)), overdrive = (e_overdrive.text.split(';') if e_overdrive is not None else []), lending_edition = (e_lending_edition.text if e_lending_edition is not None else None),
def get_doc(doc): e_ia = doc.find("arr[@name='ia']") first_pub = None e_first_pub = doc.find("int[@name='first_publish_year']") if e_first_pub is not None: first_pub = e_first_pub.text e_first_edition = doc.find("str[@name='first_edition']") first_edition = None if e_first_edition is not None: first_edition = e_first_e...
lending_editin = w.get('lending_edition_s', ''),
lending_edition = w.get('lending_edition_s', ''),
def work_object(w): ia = w.get('ia', []) obj = dict( authors = [web.storage(key='/authors/' + k, name=n) for k, n in zip(w['author_key'], w['author_name'])], edition_count = w['edition_count'], key = '/works/' + w['key'], title = w['title'], public_scan = w.get('public_scan_b', bool(ia)), lending_editin = w.get('lendin...
solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=key,author_name,author_key,title,subtitle,edition_count,ia,cover_edition_key,has_fulltext,first_publish_year,public_scan_b,lending_edition_s,overdrive_s&qt=standard&wt=json" % (q, offset, rows)
fields = ['key', 'author_name', 'author_key', 'title', 'subtitle', 'edition_count', 'ia', 'cover_edition_key', 'has_fulltext', 'first_publish_year', 'public_scan_b', 'lending_edition_s', 'overdrive_s'] fl = ','.join(fields) solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=%s&qt=standa...
def works_by_author(akey, sort='editions', page=1, rows=100): q='author_key:' + akey offset = rows * (page - 1) solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=key,author_name,author_key,title,subtitle,edition_count,ia,cover_edition_key,has_fulltext,first_publish_year,public_scan_b,l...
seeds=data.get('seeds', [])
seeds=seeds
def POST(self, user_key): # POST is allowed only for /people/foo/lists if not user_key.startswith("/people/"): raise web.nomethod() site = web.ctx.site user = site.get(user_key) if not user: raise web.notfound() if not site.can_write(user_key): raise self.forbidden() data = self.loads(web.data()) # TODO: validate d...
"seeds": data.get("seeds", [])
"seeds": seeds
def POST(self, user_key): # POST is allowed only for /people/foo/lists if not user_key.startswith("/people/"): raise web.nomethod() site = web.ctx.site user = site.get(user_key) if not user: raise web.notfound() if not site.can_write(user_key): raise self.forbidden() data = self.loads(web.data()) # TODO: validate d...
for seed in data["add"]:
process_seeds = lists_json().process_seeds for seed in process_seeds(data["add"]):
def POST(self, key): site = web.ctx.site list = site.get(key) if not list: raise web.notfound() if not site.can_write(key): raise self.forbidden() data = formats.load(web.data(), self.encoding) data.setdefault("add", []) data.setdefault("remove", []) for seed in data["add"]: list.add_seed(seed) for seed in data["...
for seed in data["remove"]:
for seed in process_seeds(data["remove"]):
def POST(self, key): site = web.ctx.site list = site.get(key) if not list: raise web.notfound() if not site.can_write(key): raise self.forbidden() data = formats.load(web.data(), self.encoding) data.setdefault("add", []) data.setdefault("remove", []) for seed in data["add"]: list.add_seed(seed) for seed in data["...
def is_admin(self): """"Returns True if the current user is in admin usergroup.""" user = web.ctx.site.get_user() return user and user.key in [m.key for m in web.ctx.site.get('/usergroup/admin').members]
def is_admin(self): """"Returns True if the current user is in admin usergroup.""" user = web.ctx.site.get_user() return user and user.key in [m.key for m in web.ctx.site.get('/usergroup/admin').members]
if not self.is_admin():
if not is_admin():
def GET(self, key): if not self.is_admin(): return render_template('permission_denied', web.ctx.path, "Permission denied.") edition = web.ctx.site.get(key) if not edition: raise web.notfound()
if web.ctx.path.startswith("/l/"): if not web.ctx.site.get(web.ctx.path): raise web.seeother("/languages/" + web.ctx.path[len("/l/"):]) if web.ctx.path.startswith("/user/"): if not web.ctx.site.get(web.ctx.path): raise web.seeother("/people/" + web.ctx.path[len("/user/"):])
def __call__(self, handler): # temp hack to handle languages and users during upstream-to-www migration if web.ctx.path.startswith("/l/"): if not web.ctx.site.get(web.ctx.path): raise web.seeother("/languages/" + web.ctx.path[len("/l/"):]) if web.ctx.path.startswith("/user/"): if not web.ctx.site.get(web.ctx.path): ra...
if not type \ or encoding is not None \
if encoding is not None \
def match(path): for pat, type, property, default_title in self.patterns: if web.re_compile('^' + pat).match(path): return type, property, default_title return None, None, None
self.infobase_conn = client.RemoteConnection(**settings["infobase_server"])
self.infobase_conn = client.RemoteConnection(settings["infobase_server"])
def __init__(self, settings): """Creates lists engine with the given settings. """ if "infobase_server" in settings: self.infobase_conn = client.RemoteConnection(**settings["infobase_server"]) elif "db" in settings: web.config.db_parameters = settings['db'] self.infobase_conn = client.LocalConnection(**settings["db"]) ...
def get_seeds(self): """Returns the all the seeds with uniform interface. """ for s in self.seeds: if isinstance(s, Thing): yield web.storage( type=s.type.key.split("/")[-1], doc=s ) else: yield web.storage( type="subject", title=s.split(":")[-1] url="/subjects" + s )
def get_subjects(self): """Returns list of subjects inferred from the seeds. Each item in the list will be a storage object with title and url. """ # sample subjects return [ web.storage(title="Cheese", url="/subjects/cheese"), web.storage(title="San Francisco", url="/subjects/place:san_francisco") ]
except (ClientException, db.ValidationException), e:
except (client.ClientException, ValidationException), e:
def POST(self, key): # only allow admin users to edit yaml if not self.is_admin(): return render.permission_denied(key, 'Permission Denied') i = web.input(body='', _comment=None) if '_save' in i: d = self.load(i.body) p = web.ctx.site.new(key, d) try: p._save(i._comment) except (ClientException, db.ValidationExceptio...
authors = [web.storage(key=key, name=tidy_name(name), url="/authors/%s/%s" % (key, urlsafe(name))) for key, name in zip(ak, an)]
authors = [web.storage(key=key, name=tidy_name(name), url="/authors/%s/%s" % (key, (urlsafe(name) if name is not None else 'noname'))) for key, name in zip(ak, an)]
def get_doc(doc): e_ia = doc.find("arr[@name='ia']") first_pub = None e_first_pub = doc.find("int[@name='first_publish_year']") if e_first_pub is not None: first_pub = e_first_pub.text e_first_edition = doc.find("str[@name='first_edition']") first_edition = None if e_first_edition is not None: first_edition = e_first_e...
types = 'authors', 'editions', 'works', 'subjects'
types = 'authors', 'editions', 'works', 'subjects', 'inside'
def cp_file(src, dst): print "copy '%s' to '%s'" % (src, dst) shutil.copy(src, dst)
def get_subjects(work):
def get_subjects(doc):
def get_subjects(work): for s in doc.get('subjects', []): yield s, '/subjects/' + s.lower().replace(' ', '_') for s in doc.get('subject_places', []): yield s, '/subjects/place:' + s.lower().replace(' ', '_') for s in doc.get('subject_people', []): yield s, '/subjects/person:' + s.lower().replace(' ', '_') for s in d...
for f in self.files:
for f in self.files.values():
def close(self): for f in self.files: f.close() self.files.clear()
query['kind'] = kind
query['kind'] = kind and kind.strip("/")
def render(self, date=None, kind=None): query = {} if date: begin_date, end_date = dateutil.parse_daterange(date) query['begin_date'] = begin_date.isoformat() query['end_date'] = end_date.isoformat() if kind: query['kind'] = kind return render_template("recentchanges/index", query)
def view(self, name, keys=None): return [web.storage(id=doc['_id'], key=doc['_id'], value=doc) for doc in self.docs]
def view(self, name, keys=None, include_docs=False): return [web.storage(id=doc['_id'], key=doc['_id'], value=doc, doc=doc) for doc in self.docs]
def view(self, name, keys=None): return [web.storage(id=doc['_id'], key=doc['_id'], value=doc) for doc in self.docs]
{"key": "subject:love", "url": "/subjects/love", "name": "Love", "count": 4}, {"key": "place:san_francisco", "url": "/subjects/place:san_francisco", "name": "San Francisco", "count": 3}
{"key": "subject:love", "url": "/subjects/love", "name": "Love", "title": "Love", "count": 4}, {"key": "place:san_francisco", "url": "/subjects/place:san_francisco", "name": "San Francisco", "title": "San Francisco", "count": 3}
def test_simple(self): doc1 = { "_id": "/works/OL1W", "editions": 10, "works": 1, "ebooks": 2, "subjects": [ {"key": "subject:love", "name": "Love", "count": 2} ] }
{"key": "subject:love", "url": "/subjects/love", "name": "Love", "count": 4}
{"key": "subject:love", "url": "/subjects/love", "name": "Love", "title": "Love", "count": 4}
def test_simple(self): doc1 = { "_id": "/works/OL1W", "editions": 10, "works": 1, "ebooks": 2, "subjects": [ {"key": "subject:love", "name": "Love", "count": 2} ] }
def get_works(self, seed, chunksize=100):
def get_works(self, seed, chunksize=1000):
def get_works(self, seed, chunksize=100): rows = couch_iterview(self.db, "seeds/seeds", key=seed, include_docs=True) return (row.doc for row in rows) """ rows = self.db.view("seeds/seeds", key=seed, include_docs=True, limit=chunksize).rows for row in rows: yield row docid = row.id while rows: rows = self.db.view("see...
def get_work_counts(self, seed, chunksize=1000): rows = couch_iterview(self.db, "counts/counts", key=seed) return (row.value for row in rows)
def get_works(self, seed, chunksize=100): rows = couch_iterview(self.db, "seeds/seeds", key=seed, include_docs=True) return (row.doc for row in rows) """ rows = self.db.view("seeds/seeds", key=seed, include_docs=True, limit=chunksize).rows for row in rows: yield row docid = row.id while rows: rows = self.db.view("see...
while rows:
while len(rows) == limit: print "db.view", viewname, docid
def couch_iterview(db, viewname, chunksize=100, **options): rows = db.view(viewname, limit=chunksize, **options).rows for row in rows: yield row docid = row.id while rows: rows = db.view(viewname, startkey_docid=docid, skip=1, limit=chunksize, **options).rows for row in rows: yield row docid = row.id
return [s for s in subjects + places + people + times if s is not None]
d = dict((s['key'], s) for s in subjects + places + people + times if s is not None) return d.values()
def get_subjects(work): subjects = [_get_subject(s, "subject:") for s in work.get("subjects", [])] places = [_get_subject(s, "place:") for s in work.get("subject_places", [])] people = [_get_subject(s, "person:") for s in work.get("subject_people", [])] times = [_get_subject(s, "time:") for s in work.get("subject_times...
last_modified = max(date['value'] for date in [work['last_modified']] + [e['last_modified'] for e in work.get('editions', [])])
dates = (doc['last_modified'] for doc in [work] + work.get('editions', []) if 'last_modified' in doc) last_modified = max(date['value'] for date in dates or [""])
def get_subjects(work): subjects = [_get_subject(s, "subject:") for s in work.get("subjects", [])] places = [_get_subject(s, "place:") for s in work.get("subject_places", [])] people = [_get_subject(s, "person:") for s in work.get("subject_people", [])] times = [_get_subject(s, "time:") for s in work.get("subject_times...
system("cat openlibrary/coverstore/schema.sql | psql coverstore")
system("psql coverstore < openlibrary/coverstore/schema.sql")
def initialize_postgres_database(): info("creating coverstore database...") system("createdb coverstore") system("cat openlibrary/coverstore/schema.sql | psql coverstore") info(" creating openlibrary database...") system("createdb openlibrary") stdout = open("var/log/install.log", 'a') info(" starting infobase serv...
if line[3] == '[' and line[-2] == ']': self.line = line[0:3] + line[4:-3] + line[-1]
if line[4] == '[' and line[-2] == ']': self.line = line[0:4] + line[5:-2] + line[-1]
def remove_brackets(self): line = self.line if line[3] == '[' and line[-2] == ']': self.line = line[0:3] + line[4:-3] + line[-1]
return [d.ip for d in web.ctx.site.get("/admin/block").ips]
doc = web.ctx.site.get("/admin/block") if doc: return [d.ip for d in doc.ips] else: return []
def get_blocked_ips(): return [d.ip for d in web.ctx.site.get("/admin/block").ips]
return subject
return seed
def get_seed(self): seed = self.key.split("/")[-1] if seed.split(":")[0] not in ["place", "person", "time"]: seed = "subject:" + seed return subject
resource_id = re.match(urn_pattern, ia_urn).group(0)
resource_id = re.match(urn_pattern, ia_urn).group(1)
def update_loan_status(self): """Update the loan status based off the status in ACS4""" urn_pattern = r'acs:\w+:(.*)' for ia_urn in self.get_lending_resources(): resource_id = re.match(urn_pattern, ia_urn).group(0) borrow.update_loan_status(resource_id)
j = simplejson.load(open('test_data/xml_expect/' + i + '_marc.xml'))
expect_filename = 'test_data/xml_expect/' + i + '_marc.xml' if os.path.exists(expect_filename): j = simplejson.load(open(expect_filename)) else: j = {}
def test_xml(self): for i in xml_samples: j = simplejson.load(open('test_data/xml_expect/' + i + '_marc.xml')) path = 'test_data/xml_input/' + i + '_marc.xml' element = etree.parse(open(path)).getroot() if element.tag != record_tag and element[0].tag == record_tag: element = element[0] rec = MarcXml(element) edition_ma...
j = simplejson.load(open('test_data/bin_expect/' + i))
expect_filename = 'test_data/bin_expect/' + i if os.path.exists(expect_filename): j = simplejson.load(open(expect_filename)) else: j = {}
def test_binary(self): for i in bin_samples: j = simplejson.load(open('test_data/bin_expect/' + i)) data = open('test_data/bin_input/' + i).read() if len(data) != int(data[:5]): data = data.decode('utf-8').encode('raw_unicode_escape') assert len(data) == int(data[:5]) rec = MarcBinary(data) edition_marc_bin = read_edit...
print "XXX updating %s" % resource_type
def update_all_loan_status(): """Update the status of all loans known to Open Library by cross-checking with the book status server""" # Get book status records of everything loaned out bss_statuses = get_all_loaned_out() bss_resource_ids = [status['resourceid'] for status in bss_statuses] for resource_type in ['epub...
def load(loc, ia): print "load", loc, ia url = archive_url + loc
def load_binary(ia): url = archive_url + ia + '/' + ia + '_meta.mrc'
def load(loc, ia): print "load", loc, ia url = archive_url + loc f = urlopen_keep_trying(url) try: edition = parse_xml.parse(f) except parse_xml.BadSubtag: return if 'title' not in edition: return edition['ocaid'] = ia write_edition(ia, edition)
try: edition = parse_xml.parse(f) except parse_xml.BadSubtag: return if 'title' not in edition: return
data = f.read() assert '<title>Internet Archive: Page Not Found</title>' not in data[:200] if len(data) != int(data[:5]): data = data.decode('utf-8').encode('raw_unicode_escape') assert len(data) == int(data[:5]) return MarcBinary(data) def load_xml(ia): url = archive_url + ia + '/' + ia + '_marc.xml' f = urlopen_keep...
def load(loc, ia): print "load", loc, ia url = archive_url + loc f = urlopen_keep_trying(url) try: edition = parse_xml.parse(f) except parse_xml.BadSubtag: return if 'title' not in edition: return edition['ocaid'] = ia write_edition(ia, edition)
write_edition(ia, edition) def write_edition(ia, edition):
write_edition(ia, edition, rec) def write_edition(ia, edition, rec):
def load(loc, ia): print "load", loc, ia url = archive_url + loc f = urlopen_keep_trying(url) try: edition = parse_xml.parse(f) except parse_xml.BadSubtag: return if 'title' not in edition: return edition['ocaid'] = ia write_edition(ia, edition)
add_lang(edition)
if ia == 'ofilhoprdigodr00mano': edition['languages'] = [{'key': '/languages/por'}] elif ia == 'dasrmischepriv00rein': edition['languages'] = [{'key': '/languages/ger'}]
def write_edition(ia, edition): loc = 'ia:' + ia add_lang(edition) q = build_query(loc, edition) authors = [] for a in q.get('authors', []): if 'key' in a: authors.append({'key': a['key']}) else: try: ret = ol.new(a, comment='new author') except: print a raise print 'ret:', ret assert isinstance(ret, basestring) author...
key = ret
key = '/b/' + re_edition_key.match(ret).group(1)
def write_edition(ia, edition): loc = 'ia:' + ia add_lang(edition) q = build_query(loc, edition) authors = [] for a in q.get('authors', []): if 'key' in a: authors.append({'key': a['key']}) else: try: ret = ol.new(a, comment='new author') except: print a raise print 'ret:', ret assert isinstance(ret, basestring) author...
add_cover_image(key, ia)
add_cover_image(ret, ia) return print 'run work finder' for a in authors: akey = a['key'] title_redirects = find_title_redirects(akey) works = find_works(akey, get_books(akey, books_query(akey)), existing=title_redirects) works = list(works) updated = update_works(akey, works, do_updates=True)
def write_edition(ia, edition): loc = 'ia:' + ia add_lang(edition) q = build_query(loc, edition) authors = [] for a in q.get('authors', []): if 'key' in a: authors.append({'key': a['key']}) else: try: ret = ol.new(a, comment='new author') except: print a raise print 'ret:', ret assert isinstance(ret, basestring) author...
db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': start})
db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': hide_start}) last_updated = None
def hide_books(start): mend = [] fix_works = set() db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': start}) for row in db_iter: ia = row.identifier i...
if 'printdisabled' in collections:
if 'printdisabled' in collections or 'lendinglibrary' in collections:
def hide_books(start): mend = [] fix_works = set() db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': start}) for row in db_iter: ia = row.identifier i...
hide_books(start)
def hide_books(start): mend = [] fix_works = set() db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': start}) for row in db_iter: ia = row.identifier i...
if 'printdisabled' not in collections: continue ia = row.identifier if re_census.match(ia): print 'skip census for now:', ia
if 'printdisabled' in collections or 'lendinglibrary' in collections: continue if ia.startswith('annualreportspri'): print 'skipping:', ia continue if 'shenzhentest' in collections: continue if re_census.match(ia) or ia.startswith('populationschedu') or ia.startswith('michigancensus') or 'census00reel' in ia or ia.star...
def hide_books(start): mend = [] fix_works = set() db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': start}) for row in db_iter: ia = row.identifier i...
loc, rec = get_ia(ia) except (KeyboardInterrupt, NameError): raise except NoMARCXML: write_log(ia, when, "no MARCXML") continue
formats = marc_formats(ia)
def hide_books(start): mend = [] fix_works = set() db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': start}) for row in db_iter: ia = row.identifier i...
if loc is None: write_log(ia, when, "error: no loc ")
if not any(formats.values()): print 'skipping, no MARC' continue if all(formats.values()): use_binary = bad_ia_xml(ia) else: use_binary = formats['bin'] if use_binary: rec = get_marc_ia(ia) else: try: rec = get_ia(ia) except (KeyboardInterrupt, NameError): raise except NoMARCXML: write_log(ia, when, "no MARCXML") conti...
def hide_books(start): mend = [] fix_works = set() db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': start}) for row in db_iter: ia = row.identifier i...
print loc, rec if not loc.endswith('.xml'): print "not XML" write_log(ia, when, "error: not XML") continue
print rec
def hide_books(start): mend = [] fix_works = set() db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': start}) for row in db_iter: ia = row.identifier i...
load(loc, ia)
load(ia, use_binary=use_binary)
def hide_books(start): mend = [] fix_works = set() db_iter = db.query("select identifier, collection, updated from metadata where (noindex is not null or curatestate='dark') and mediatype='texts' and scandate is not null and updated > $start order by updated", {'start': start}) for row in db_iter: ia = row.identifier i...
overdrive_id = e.get('identifiers', {}).get('overdrive_id', None)
overdrive_id = e.get('identifiers', {}).get('overdrive', None)
def get_pub_year(e): pub_date = e.get('publish_date', None) if pub_date: m = re_year.search(pub_date) if m: return m.group(1)
e['overdrive'] = overdrive
print 'overdrive:', overdrive_id e['overdrive'] = overdrive_id
def get_pub_year(e): pub_date = e.get('publish_date', None) if pub_date: m = re_year.search(pub_date) if m: return m.group(1)
all_overdrive.add(e['overdrive'])
all_overdrive.update(e['overdrive'])
def get_pub_year(e): pub_date = e.get('publish_date', None) if pub_date: m = re_year.search(pub_date) if m: return m.group(1)
for i, j in xml_samples: f = open('test_data/' + i + '_marc.xml') element = etree.parse(f).getroot()
for i in xml_samples: j = simplejson.load(open('test_data/xml_expect/' + i + '_marc.xml')) path = 'test_data/xml_input/' + i + '_marc.xml' element = etree.parse(open(path)).getroot()
def test_xml(self): for i, j in xml_samples: f = open('test_data/' + i + '_marc.xml') element = etree.parse(f).getroot() if element.tag != record_tag and element[0].tag == record_tag: element = element[0] rec = MarcXml(element) edition_marc_xml = read_edition(rec) self.assertEqual(sorted(edition_marc_xml.keys()), sorte...
for i, j in bin_samples: f = open('test_data/' + i) rec = MarcBinary(f.read())
for i in bin_samples: j = simplejson.load(open('test_data/bin_expect/' + i)) data = open('test_data/bin_input/' + i).read() if len(data) != int(data[:5]): data = data.decode('utf-8').encode('raw_unicode_escape') assert len(data) == int(data[:5]) rec = MarcBinary(data)
def test_binary(self): for i, j in bin_samples: f = open('test_data/' + i) rec = MarcBinary(f.read()) edition_marc_bin = read_edition(rec) #print 'result:' #pprint(edition_marc_bin) #print #print 'expected:' #pprint(j) #print self.assertEqual(sorted(edition_marc_bin.keys()), sorted(j.keys())) print i for k in edition_m...
print i
def test_binary(self): for i, j in bin_samples: f = open('test_data/' + i) rec = MarcBinary(f.read()) edition_marc_bin = read_edition(rec) #print 'result:' #pprint(edition_marc_bin) #print #print 'expected:' #pprint(j) #print self.assertEqual(sorted(edition_marc_bin.keys()), sorted(j.keys())) print i for k in edition_m...
f = open('test_data/' + i)
f = open('test_data/bin_input/' + i)
def test_binary(self): for i, j in bin_samples: f = open('test_data/' + i) rec = MarcBinary(f.read()) edition_marc_bin = read_edition(rec) #print 'result:' #pprint(edition_marc_bin) #print #print 'expected:' #pprint(j) #print self.assertEqual(sorted(edition_marc_bin.keys()), sorted(j.keys())) print i for k in edition_m...
reutrn get_message_from_template("messages", name, *args)
return get_message_from_template("messages", name, *args)
def get_message(name, *args): """Return message with given name from messages.tmpl template""" reutrn get_message_from_template("messages", name, *args)
for t in types
for t in types:
def cp_file(src, dst): print "copy '%s' to '%s'" % (src, dst) shutil.copy(src, dst)
if i.file is not None:
if i.file is not None and hasattr(i.file, 'value'):
def upload(self, key, i): """Uploads a cover to coverstore and returns the response.""" olid = key.split("/")[-1] if i.file is not None: data = i.file.value else: data = None if i.url and i.url.strip() == "http://": i.url = ""
for row in self._couch_view("ol/lists", keys=keys, group=True):
for row in self._seeds_view(keys=keys, group=True):
def _get_seed_summary(self): rawseeds = self._get_rawseeds() keys = crossproduct(rawseeds, ['works', 'editions', 'ebooks']) d = dict((seed, {"editions": 0, "works": 0, "ebooks": 0}) for seed in rawseeds) for row in self._couch_view("ol/lists", keys=keys, group=True): key, name = row.key d[key][name] = row.value retu...
keys = self._site.things(q) return self._site.get_many(keys)
keys = web.ctx.site.things(q) return web.ctx.site.get_many(keys)
def get_lists(self): q = { "type": "/type/list", "seeds": {"key": self.key} } keys = self._site.things(q) return self._site.get_many(keys)
for k in 'has_fulltext': if k not in param: continue
k = 'has_fulltext' if k in param:
def run_solr_query(param = {}, rows=100, page=1, sort=None): q_list = [] if 'q' in param: q_param = param['q'].strip() else: q_param = None offset = rows * (page - 1) if q_param: if q_param == '*:*' or re_fields.match(q_param): q_list.append(q_param) else: isbn = read_isbn(q_param) if isbn: q_list.append('isbn:(%s)' % ...
return web.storage(
obj = dict(
def work_object(w): return web.storage( authors = [web.storage(key='/authors/' + k, name=n) for k, n in zip(w['author_key'], w['author_name'])], edition_count = w['edition_count'], key = '/works/' + w['key'], title = w['title'], cover_edition_key = w.get('cover_edition_key', None), first_publish_year = (w['first_publis...
if w.get('has_fulltext', None): obj['has_fulltext'] = w['has_fulltext'] return web.storage(obj)
def work_object(w): return web.storage( authors = [web.storage(key='/authors/' + k, name=n) for k, n in zip(w['author_key'], w['author_name'])], edition_count = w['edition_count'], key = '/works/' + w['key'], title = w['title'], cover_edition_key = w.get('cover_edition_key', None), first_publish_year = (w['first_publis...
if w.get('has_fulltext', None) == 'true': i['has_fulltext'] = 'true'
if w.get('has_fulltext', None): i['has_fulltext'] = w['has_fulltext']
def get_covers(limit=20): collect = [] for w in works if limit is None else works[:limit]: i = { 'key': w.key, 'title': w.title, 'authors': [dict(a) for a in w.authors], 'edition_count': w.edition_count, } if w.get('cover_edition_key', None): i['cover_edition_key'] = w.cover_edition_key if w.get('has_fulltext', None) =...
class subject_search(delegate.page):
class search_inside(delegate.page):
def read_from_archive(ia): meta_xml = 'http://www.archive.org/download/' + ia + '/' + ia + '_meta.xml' tree = etree.parse(meta_xml) root = tree.getroot() item = {} fields = ['title', 'creator', 'publisher', 'date', 'language'] for k in 'title', 'date', 'publisher': v = root.find(k) if v is not None: item[k] = v.text ...
solr_select = solr_select_url + "?fl=ia,body_length,page_count&hl=true&hl.fl=body&hl.snippets=%d&hl.mergeContiguous=true&hl.usePhraseHighlighter=true&hl.simple.pre={{{&hl.simple.post=}}}&hl.fragsize=%d&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=*&qt=standard&wt=json" % (snippets, fragsize, web.urlquote(q), offset, limit)
solr_select = solr_select_url + "?fl=ia,body_length,page_count&hl=true&hl.fl=body&hl.snippets=%d&hl.mergeContiguous=true&hl.usePhraseHighlighter=true&hl.simple.pre={{{&hl.simple.post=}}}&hl.fragsize=%d&q.op=AND&q=%s&start=%d&rows=%d&qf=body&qt=standard&wt=json" % (snippets, fragsize, web.urlquote(q), offset, limit) pri...
def get_results(q, offset=0, limit=100, snippets=3, fragsize=200): q = escape_bracket(q) solr_select = solr_select_url + "?fl=ia,body_length,page_count&hl=true&hl.fl=body&hl.snippets=%d&hl.mergeContiguous=true&hl.usePhraseHighlighter=true&hl.simple.pre={{{&hl.simple.post=}}}&hl.fragsize=%d&q.op=AND&q=%s&fq=&start=%d&ro...
return simplejson.loads(json_data)
try: return simplejson.loads(json_data) except: m = re_query_parser_error.search(json_data) return { 'error': web.htmlunquote(m.group(1)) }
def get_results(q, offset=0, limit=100, snippets=3, fragsize=200): q = escape_bracket(q) solr_select = solr_select_url + "?fl=ia,body_length,page_count&hl=true&hl.fl=body&hl.snippets=%d&hl.mergeContiguous=true&hl.usePhraseHighlighter=true&hl.simple.pre={{{&hl.simple.post=}}}&hl.fragsize=%d&q.op=AND&q=%s&fq=&start=%d&ro...
url = self.base_url + "/select?" + urllib.urlencode(params, doseq=True)
url = self.base_url + "/select?" + urlencode(params, doseq=True)
def select(self, query, fields=None, facets=None, rows=None, start=None, doc_wrapper=None, facet_wrapper=None, **kw): """Execute a solr query. query can be a string or a dicitonary. If query is a dictionary, query is constucted by concatinating all the key-value pairs with AND condition. """ params = {'wt': 'json'} f...
where += " AND t.author_id IN (SELECT thing_id FROM account WHERE bot == 't')"
where += " AND t.author_id IN (SELECT thing_id FROM account WHERE bot = 't')"
def edits(self, today, tomorrow, bots=False): tables = 'version v, transaction t' where = 'v.transaction_id=t.id AND t.created >= date($today) AND t.created < date($tomorrow)'
include_docs="true")
include_docs="true", stale="ok")
def get_editions(self, limit=50, offset=0, _raw=False): """Returns the editions objects belonged to this list ordered by last_modified. When _raw=True, the edtion dicts are returned instead of edtion objects. """ d = self._editions_view(self._get_rawseeds(), skip=offset, limit=limit, sort="last_modified", reverse="tru...
return web.re_compile(r'([:(){}])').sub(r'\\\1', value)
special_chars = '+-&|!(){}[]^"~*?:\\' pattern = "([%s])" % re.escape(special_chars) quote = '"' return quote + web.re_compile(pattern).sub(r'\\\1', value) + quote
def escape(value): return web.re_compile(r'([:(){}])').sub(r'\\\1', value)
suggestions = root.find("lst[@name='spellcheck']").find("lst[@name='suggestions']")
spellcheck = root.find("lst[@name='spellcheck']")
def do_search(param, sort, page=1, rows=100): (reply, solr_select, q_list) = run_solr_query(param, rows, page, sort) is_bad = False if reply.startswith('<html'): is_bad = True if not is_bad: try: root = XML(reply) except XMLSyntaxError: is_bad = True if is_bad: m = re_pre.search(reply) return web.storage( facet_counts ...
for e in suggestions: print e.tag assert e.tag == 'lst' a = e.attrib['name'] if a in spell_map: continue spell_map[a] = e.find("arr[@name='suggestion']")[0].text
if spellcheck: for e in spellcheck.find("lst[@name='suggestions']"): assert e.tag == 'lst' a = e.attrib['name'] if a in spell_map: continue spell_map[a] = e.find("arr[@name='suggestion']")[0].text
def do_search(param, sort, page=1, rows=100): (reply, solr_select, q_list) = run_solr_query(param, rows, page, sort) is_bad = False if reply.startswith('<html'): is_bad = True if not is_bad: try: root = XML(reply) except XMLSyntaxError: is_bad = True if is_bad: m = re_pre.search(reply) return web.storage( facet_counts ...
return self.query({"key": keys, "*": None})
return self.query({"key": keys, "*": None, "limit": len(keys)})
def get_many(self, keys): return self.query({"key": keys, "*": None})
if config.get('memcache_servers'): conn = MemcacheMiddleware(conn, config.get('memcache_servers'))
def create_connection(): if config.get('infobase_server'): return client.connect(type='remote', base_url=config.infobase_server) elif config.get('db_parameters'): return client.connect(type='local', **config.db_parameters) else: raise Exception("db_parameters are not specified in the configuration")
re_parens = re.compile('^(.*?)(?: \(.+ (?:Edition|Press|Print|Novels|Mysteries|Book Series|Classics Library|Classics|Books)\))+$', re.I)
re_parens = re.compile('^(.*?)(?: \(.+ (?:Edition|Press|Print|Plays|Collection|Publication|Novels|Mysteries|Book Series|Classics Library|Classics|Books)\))+$', re.I)
def has_dot(s): return s.endswith('.') and not re_skip.search(s)
print 'bad XML', ia print url
def get_ia_work_title(ia): url = 'http://www.archive.org/download/' + ia + '/' + ia + '_marc.xml' try: root = etree.parse(urlopen(url)).getroot() except KeyboardInterrupt: raise except: print 'bad XML', ia print url return #print etree.tostring(root) e = root.find(ns_data + "[@tag='240']") if e is None: print 'no work ...
print 'no work title', ia print url
def get_ia_work_title(ia): url = 'http://www.archive.org/download/' + ia + '/' + ia + '_marc.xml' try: root = etree.parse(urlopen(url)).getroot() except KeyboardInterrupt: raise except: print 'bad XML', ia print url return #print etree.tostring(root) e = root.find(ns_data + "[@tag='240']") if e is None: print 'no work ...
bad_titles = ['Publications', 'Works', 'Report', \
bad_titles = ['Publications', 'Works. English', 'Works', 'Report', \
def get_work_title(e): # use first work title we find in source MARC records wt = None for src_type, src in get_marc_src(e): if src_type == 'ia': wt = get_ia_work_title(src) if wt: wt = wt.strip('. ') if wt: break continue assert src_type == 'marc' data = None #print 'get from archive:', src try: data = get_data(src) e...
'Sermons', 'Correspondence', 'Bills']
'Sermons', 'Correspondence', 'Bills', 'Selections', 'Selected works', 'Selected works. English']
def get_work_title(e): # use first work title we find in source MARC records wt = None for src_type, src in get_marc_src(e): if src_type == 'ia': wt = get_ia_work_title(src) if wt: wt = wt.strip('. ') if wt: break continue assert src_type == 'marc' data = None #print 'get from archive:', src try: data = get_data(src) e...
if title_and_subtitle in ['Publications', 'Works', 'Report', \ 'Letters', 'Calendar', 'Bulletin', 'Plays', \ 'Sermons', 'Correspondence', 'Bills']: continue
def get_books(akey, query): for e in query: if not e.get('title', None): continue
if e['table_of_contents'][0]['type'] == '/type/text':
if e['table_of_contents'][0].get('type', None) == '/type/text':
def get_books(akey, query): for e in query: if not e.get('title', None): continue
w = ol.get(wkey)
if wkey.startswith('DUP'): continue try: w = ol.get(wkey) except: print wkey raise
def get_existing_works(akey): q = { 'type':'/type/work', 'authors': {'author': {'key': akey}}, 'limit': 500, } seen = set() for wkey in ol.query(q): if wkey in seen: continue # skip dups w = ol.get(wkey) if w['type'] == '/type/redirect': continue yield w
def fix_up_authors(w, akey, editions): seen_akey = False need_save = False for a in w.get('authors', []): obj = withKey(a['author']['key']) if obj['type']['key'] == '/type/redirect': a['author']['key'] = obj['location'] obj = withKey(a['author']['key']) assert obj['type']['key'] == '/type/author' need_save = True if ak...
def add_detail_to_work(i, j): if 'subtitle' in i: j['subtitle'] = i['subtitle'] if 'subjects' in i: add_subjects_to_work(i['subjects'], j)
print 'redirect found'
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
e = withKey(ekey) e['works'] = [Reference(wkey)]
e = ol.get(ekey) e['works'] = [{'key': wkey}]
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
print 'no redirects left'
print >> fh_log, 'no redirects left'
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
print 'save redirects' ol.save_many(fix_redirects, "merge works")
print >> fh_log, 'save redirects' try: ol.save_many(fix_redirects, "merge works") except: for r in fix_redirects: print r raise
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
print 'edition_to_work' for k, v in edition_to_work.iteritems(): print ' %s: %s' % (k, v)
print >> fh_log, 'edition_to_work:' print >> fh_log, `edition_to_work` print >> fh_log print >> fh_log, 'work_to_edition' print >> fh_log, `work_to_edition` print >> fh_log works_updated_this_session = set() matched_works = defaultdict(list) print >> fh_log, 'start updating works'
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
print print w['title'], len(w['editions']) existing = set()
print >> fh_log print >> fh_log, `w['title']`, len(w['editions'])
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
existing.update(edition_to_work[e['key']]) print 'existing:', existing
print >> fh_log, e print >> fh_log, 'works updated this session:', list(works_updated_this_session) existing = defaultdict(int) for e in w['editions']: ekey = e['key'] if isinstance(e, dict) else e for wkey in edition_to_work[ekey]: existing[wkey] += 1 print >> fh_log, 'existing works:', existing
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
ol_work = { 'title': w['title'], 'type': '/type/work', 'authors': [{'type':'/type/author_role', 'author': akey}], } add_detail_to_work(w, ol_work) print ol_work if do_updates: wkey = ol.new(ol_work, comment='work found') work_keys.append(wkey) print 'new work:', wkey, `w['title']` else: print 'new work:', `w['title']` ...
new_work(akey, w, do_updates, fh_log)
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
if cur_work['title'] != w['title']: print 'new title:', key, `cur_work['title']`, '->', `w['title']` existing_work = ol.get(key) existing_work['title'] = w['title'] add_detail_to_work(w, existing_work) print 'existing:', existing_work print 'subtitle:', existing_work.get('subtitle', 'n/a') if do_updates: ol.save(key,...
w['need_save'] = True matched_works[key].append(w)
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
use_key = min(existing, key=lambda i: int(re_work_key.match(i).group(1)))
use_key = max(existing.iteritems(), key=lambda i:i[1])[0] print use_key, len(w['editions']), w['title'], if use_key in works_updated_this_session: print 'already seen' print assert use_key not in works_updated_this_session works_updated_this_session.add(use_key)
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
print 'merge work:', key, `w['title']`, 'to', use_key
print >> fh_log, 'merge works:', `w['title']`, 'to', use_key
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
e['works'] = [Reference(use_key)]
e['works'] = [{'key': use_key}]
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
if cur_work['title'] != w['title'] \
need_save = fix_up_authors(cur_work, akey, w['editions']) if need_save or cur_work['title'] != w['title'] \
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
print 'update work title:', key, `cur_work['title']`, '->', `w['title']`
print 'update work title:', use_key, `cur_work['title']`, '->', `w['title']`
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...
print 'existing:', existing_work print 'subtitle:', existing_work.get('subtitle', 'n/a')
print >> fh_log, 'existing:', existing_work print >> fh_log, 'subtitle:', existing_work.get('subtitle', 'n/a')
def update_works(akey, works, do_updates=False): # we can now look up all works by an author while True: # until redirects repaired q = {'type':'/type/edition', 'authors': akey, 'works': None} work_to_edition = defaultdict(set) edition_to_work = defaultdict(set) for e in query_iter(q): if e.get('works', None): for w in...