rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
cur = work_by_key[wkey]['title'] print ' ', wkey, cur == w['title'], `cur` print len(work_to_edition), len(all_existing) assert len(work_to_edition) == len(all_existing)
cur = work_by_key[wkey].get('title', None) print >> fh_log, ' ', wkey, cur == w['title'], `cur` print >> fh_log, len(work_to_edition), len(all_existing) if len(work_to_edition) != len(all_existing): print >> fh_log, 'work count mismatch !!!!' work_set = set(work_to_edition.iterkeys()) print >> fh_log, 'diff:', work_s...
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...
return work_keys
return [withKey(key) for key in work_keys]
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...
work_keys = update_works(akey, works, do_updates=True) for key in work_keys: w = ol.get(key) if 'cover_edition' not in w: print 'no cover found' update_work(withKey(key), debug=True) if work_keys: requests = ['<commit />'] solr_update(requests, debug=True)
to_update = update_works(akey, works, do_updates=True) requests = [] for w in to_update: requests += update_work(w) if to_update: solr_update(requests + ['<commit />'], debug=True) requests = update_author(akey) solr_update(requests + ['<commit/>'], index='authors', debug=True)
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...
path = "(/(?:people|books|works|authors|subjects)/\w+)/lists"
path = "(/(?:people|books|works|authors|subjects)/[^/]+)/lists"
def POST(self, key): doc = web.ctx.site.get(key) if doc is None or doc.type.key != '/type/list': raise web.notfound() doc = { "key": key, "type": {"key": "/type/delete"} } try: result = web.ctx.site.save(doc, action="lists", comment="Deleted list.") except client.ClientException, e: web.ctx.status = e.status web.heade...
path = property(lambda: web.ctx.path) home = property(lambda: web.ctx.home) domain = property(lambda: web.ctx.host)
path = property(lambda self: web.ctx.path) home = property(lambda self: web.ctx.home) domain = property(lambda self: web.ctx.host)
def sprintf(s, *a, **kw): args = kw or a if args: return s % args else: return s
if t in stopwords:
if t.lower() in stopwords:
def fuzzy_find(value, options, stopwords=[]): """Try find the option nearest to the value. >>> fuzzy_find("O'Reilly", ["O'Reilly Inc", "Addison-Wesley"]) "O'Reilly Inc" """ if not options: return value rx = web.re_compile("[-_\.&, ]+") # build word frequency d = defaultdict(list) for option in options: for t in rx.s...
m = web.re_compile('(\d\d)(\d\d)(\d\d)(\d{6})\..*').match(os.path.basename(path))
m = web.re_compile('(\d\d)(\d\d)(\d\d)(\d{6})').match(web.numify(os.path.basename(path)))
def parse_error(path): html = open(path).read(10000) soup = BeautifulSoup(html) h1 = web.htmlunquote(soup.body.h1.string or "") h2 = web.htmlunquote(soup.body.h2.string or "") message = h1.split('at')[0].strip() + ': ' + (h2 and h2.splitlines()[0]) code, url = [web.htmlunquote(td.string) for td in soup.body.table.fin...
def db_lookup():
def db_lookup(field, key, publish_year=None):
def db_lookup(): sql = 'select sum(ebook_count) as num from subjects where field=$field and key=$key' if publish_year: if isinstance(publish_year, list): sql += ' and publish_year between $y1 and $y2' (y1, y2) = publish_year else: sql += ' and publish_year=$publish_year' return list(ebook_count_db.query(sql, vars=local...
total = db_lookup()
total = db_lookup(field, key, publish_year)
def db_lookup(): sql = 'select sum(ebook_count) as num from subjects where field=$field and key=$key' if publish_year: if isinstance(publish_year, list): sql += ' and publish_year between $y1 and $y2' (y1, y2) = publish_year else: sql += ' and publish_year=$publish_year' return list(ebook_count_db.query(sql, vars=local...
return db_lookup()
return db_lookup(field, key, publish_year)
def db_lookup(): sql = 'select sum(ebook_count) as num from subjects where field=$field and key=$key' if publish_year: if isinstance(publish_year, list): sql += ' and publish_year between $y1 and $y2' (y1, y2) = publish_year else: sql += ' and publish_year=$publish_year' return list(ebook_count_db.query(sql, vars=local...
publisher = publisher and fuzzy_find(publisher, work.publisher, stopwords=["publisher", "publishers", "and"])
publisher = publisher and fuzzy_find(publisher, work.publisher, stopwords=("publisher", "publishers", "and"))
def try_edition_match(self, work=None, title=None, author_key=None, publisher=None, publish_year=None, id_name=None, id_value=None): # insufficient data if not publisher and not publish_year and not id_value: return q = {} work and q.setdefault('key', work.key.split("/")[-1]) title and q.setdefault('title', title) au...
if work_data and not delete:
if work_data:
def save(self, formdata): """Update work and edition documents according to the specified formdata.""" comment = formdata.pop('_comment', '')
return []
return
def read_subject(subjects): if not subjects: return [] f = StringIO(subjects.encode('utf-8')) # no unicode in csv module return [s.decode('utf-8') for s in csv.reader(f, dialect='excel', skipinitialspace=True).next()]
return [s.decode('utf-8') for s in csv.reader(f, dialect='excel', skipinitialspace=True).next()] work.subjects = read_subject(work.get('subjects', '')) work.subject_places = read_subject(work.get('subject_places', '')) work.subject_times = read_subject(work.get('subject_times', '')) work.subject_people = read_subject(w...
dedup = set() for s in csv.reader(f, dialect='excel', skipinitialspace=True).next(): s = s.decode('utf-8') if s.lower() not in dedup: yield s dedup.add(s.lower()) work.subjects = list(read_subject(work.get('subjects', ''))) work.subject_places = list(read_subject(work.get('subject_places', ''))) work.subject_times = l...
def read_subject(subjects): if not subjects: return [] f = StringIO(subjects.encode('utf-8')) # no unicode in csv module return [s.decode('utf-8') for s in csv.reader(f, dialect='excel', skipinitialspace=True).next()]
for k in ['excerpts', 'links']:
for k in ('excerpts', 'links'):
def read_subject(subjects): if not subjects: return [] f = StringIO(subjects.encode('utf-8')) # no unicode in csv module return [s.decode('utf-8') for s in csv.reader(f, dialect='excel', skipinitialspace=True).next()]
work = trim_doc(work) return work
return trim_doc(work)
def read_subject(subjects): if not subjects: return [] f = StringIO(subjects.encode('utf-8')) # no unicode in csv module return [s.decode('utf-8') for s in csv.reader(f, dialect='excel', skipinitialspace=True).next()]
has_fulltext = doc.find("bool[@name='has_fulltext']") == 'true',
has_fulltext = (doc.find("bool[@name='has_fulltext']").text == 'true'),
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...
q_list.extend('(' + ' OR '.join('%s:(%s)' % (f, t) for f in non_key_fields) + ')' for t.lower() in terms if t not in stop)
q_list.extend('(' + ' OR '.join('%s:(%s)' % (f, t.lower()) for f in non_key_fields) + ')' for t in terms if t.lower() not in stop)
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)' % ...
if cover and cover > 0: print "\t".join([str(cover), key, ",".join(isbns)])
try: if cover and cover > 0: print "\t".join([str(cover), key, ",".join(isbns)]) except: print >> sys.stderr, doc print >> sys.stderr, (key, cover, isbns) raise
def main(filename): for tokens in read_tsv(filename): json = tokens[-1] doc = simplejson.loads(json) cover = doc.get('covers') and doc.get('covers')[0] isbns = doc.get('isbn_10', []) + doc.get('isbn_13', []) key = doc['key'] if cover and cover > 0: print "\t".join([str(cover), key, ",".join(isbns)])
import sys
def main(filename): for tokens in read_tsv(filename): json = tokens[-1] doc = simplejson.loads(json) cover = doc.get('covers') and doc.get('covers')[0] isbns = doc.get('isbn_10', []) + doc.get('isbn_13', []) key = doc['key'] if cover and cover > 0: print "\t".join([str(cover), key, ",".join(isbns)])
if result[0] in string.digits:
if not result: return result elif result[0] in string.digits:
def datestr(then, now=None, lang=None): """Internationalized version of web.datestr.""" result = web.datestr(then, now) if result[0] in string.digits: # eg: 2 milliseconds ago t, message = result.split(' ', 1) return _("%d " + message) % int(t) else: return format_date(then, lang=lang)
solr_select = solr_author_select_url + "?q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=*&qt=standard&wt=json" % (web.urlquote(q), offset, limit)
solr_select = solr_edition_select_url + "?q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=*&qt=standard&wt=json" % (web.urlquote(q), offset, limit)
def get_results(q, offset=0, limit=100): solr_select = solr_author_select_url + "?q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=*&qt=standard&wt=json" % (web.urlquote(q), offset, limit) return json.loads(urllib.urlopen(solr_select).read())
os.execpv(INTERP, [INTERP] + [sys.argv], env)
os.execvpe(INTERP, [INTERP] + [sys.argv], env)
def setup_virtualenv(): """Creates a new virtualenv and exec this script using python from that virtual env. """ global INTERP pyenv = os.path.expanduser(config['virtualenv']) INTERP = pyenv + "/bin/python" if sys.executable != INTERP: info("creating virtualenv at", pyenv) system("virtualenv " + pyenv) info("restart...
for author in work_data.get("authors", []):
for author in work_data.get("authors") or []:
def save(self, formdata): """Update work and edition documents according to the specified formdata.""" comment = formdata.pop('_comment', '')
for w in works if limit is None else works[:limit]
for w in works if limit is None else works[:limit]:
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], } if w.get('cover_edition_key', None): i['cover_edition_key'] = w.cover_edition_key collect.append(i) return collect
yield doc['key'], 'author', author_db[olid] yield akey, 'work', doc['key']
try: yield doc['key'], 'author', author_db[olid] yield akey, 'work', doc['key'] except KeyError: pass
def process_work(doc, author_db): doc = fix_subjects(doc) properties = [ "title", "subtitle", "translated_titles", "other_titles", "authors", "subjects", "subject_places", "subject_people", "subject_times", "genres", ] yield doc['key'], "json", simplejson.dumps(subdict(doc, properties)) authors = [a['author']['key'] ...
tjoin = "\t".join
tjoin = lambda *cols: "\t".join([web.safestr(c) for c in cols]) + "\n"
def write(self, tuples): tjoin = "\t".join for key, property, value in tuples: self.get_file(key).write(tjoin([key, property, value]) + "\n")
self.get_file(key).write(tjoin([key, property, value]) + "\n")
self.get_file(key).write(tjoin(key, property, value))
def write(self, tuples): tjoin = "\t".join for key, property, value in tuples: self.get_file(key).write(tjoin([key, property, value]) + "\n")
from openlibrary.core import processors
from openlibrary.core.processors.invalidation import InvalidationProcessor
def setup_invalidation_processor(): from openlibrary.core import processors config = infogami.config.get("invalidation", {}) prefixes = config.get('prefixes', []) timeout = config.get("timeout", 60) cookie_name = config.get("cookie", "invalidation_timestamp") print "prefixes", prefixes print "timeout", timeout if p...
print "prefixes", prefixes print "timeout", timeout
def setup_invalidation_processor(): from openlibrary.core import processors config = infogami.config.get("invalidation", {}) prefixes = config.get('prefixes', []) timeout = config.get("timeout", 60) cookie_name = config.get("cookie", "invalidation_timestamp") print "prefixes", prefixes print "timeout", timeout if p...
p = processors.InvalidationProcessor(prefixes, timeout=timeout, cookie_name=cookie_name)
p = InvalidationProcessor(prefixes, timeout=timeout, cookie_name=cookie_name)
def setup_invalidation_processor(): from openlibrary.core import processors config = infogami.config.get("invalidation", {}) prefixes = config.get('prefixes', []) timeout = config.get("timeout", 60) cookie_name = config.get("cookie", "invalidation_timestamp") print "prefixes", prefixes print "timeout", timeout if p...
self.key = key
self.key = value
def __init__(self, list, value): self._list = list if isinstance(value, basestring): self.document = None self.key = key self.type = "subject" else: self.document = value self.key = value.key type = self.document.type.key if type == "/type/edition": self.type = "edition" elif type == "/type/work": self.type = "work"...
solr_select += ''.join('&fq=%s:"%s"' % (k, l) for l in v if l)
solr_select += ''.join('&fq=%s:"%s"' % (k, url_quote(l)) for l in v if l)
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 h.safesort(self._site.get_many(keys), reverse=True, lambda key=list: list.last_update)
return h.safesort(self._site.get_many(keys), reverse=True, key=lambda list: list.last_update)
def _get_lists(self): q = { "type": "/type/list", "seeds": {"key": self.key}, "limit": 1000 } keys = self._site.things(q) return h.safesort(self._site.get_many(keys), reverse=True, lambda key=list: list.last_update)
return re_bracket.sub(lambda m:'\\'+m.group(), q)
esc_q = re_bracket.sub(lambda m:'\\'+m.group(), q) return esc_q if 'ia:' in q else esc_q.replace(':', '\\:')
def escape_bracket(q): if re_solr_range.search(q): return q return re_bracket.sub(lambda m:'\\'+m.group(), q)
if doc.get('has_fulltext', None) == 'true': w['has_fulltext'] = 'true'
if doc.get('has_fulltext', None): w['has_fulltext'] = true w['ia'] = doc['ia'][0]
def subjects_covers(path_info): i = web.input(offset=0, limit=12) try: offset = int(i.offset) limit = int(i.limit) except ValueError: return [] (subject_type, key, full_key, q) = read_subject(path_info) 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...
if w.get('has_fulltext', None) == 'true': i['has_fulltext'] = 'true'
if w.get('has_fulltext', None): i['has_fulltext'] = w['has_fulltext'] i['ia'] = w['ia'][0]
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) =...
work['_rev'] = old_work['_rev']
if "_rev" in old_work: work['_rev'] = old_work['_rev']
def update_work(self, ctx, work, get=None, save=None): """Adds/Updates the given work in the database. """ get = get or self.db.get save = save or self.db.save logging.info("works_db: updating work %s", work['key']) key = work['key'] old_work = get(key, {}) if old_work: work['_rev'] = old_work['_rev'] work['editions'...
if i.attrib['tag'] == '':
tag = i.attrib['tag'] if tag == '':
def read_fields(self, want): want = set(want)
assert i.attrib['tag'].isdigit()
if tag == 'FMT': continue if not tag.isdigit(): non_digit = True else: if tag[0] != '9' and non_digit: raise BadSubtag
def read_fields(self, want): want = set(want)
key = web.ctx.site._request("/olid_to_key?olid=" + key.split("/")[-1]).key
olid = web.safestr(key).split("/")[-1] key = web.ctx.site._request("/olid_to_key?" + urllib.urlencode({"olid": olid})).key
def get_object(self, key): obj = web.ctx.site.get(key) if obj is None and key.startswith("/a/"): key = "/authors/" + key[len("/a/"):] obj = key and web.ctx.site.get(key) if obj is None and key.startswith("/b/"): key = "/books/" + key[len("/b/"):] obj = key and web.ctx.site.get(key) if obj is None and web.re_compile(r...
def run_solr_query(param = {}, rows=100, page=1, sort_by_edition_count=True):
def run_solr_query(param = {}, rows=100, page=1, sort=None):
def run_solr_query(param = {}, rows=100, page=1, sort_by_edition_count=True): q_list = [] if 'q' in param: q_param = param['q'].strip() else: q_param = None offset = rows * (page - 1) query_params = dict((k, url_quote(param[k])) for k in ('title', 'publisher', 'isbn', 'oclc', 'lccn', 'first_sentence', 'contribtor', 'au...
if sort_by_edition_count: solr_select += "&sort=edition_count+desc"
if sort: solr_select += "&sort=" + url_quote(sort)
def run_solr_query(param = {}, rows=100, page=1, sort_by_edition_count=True): q_list = [] if 'q' in param: q_param = param['q'].strip() else: q_param = None offset = rows * (page - 1) query_params = dict((k, url_quote(param[k])) for k in ('title', 'publisher', 'isbn', 'oclc', 'lccn', 'first_sentence', 'contribtor', 'au...
(root, search_url, solr_select, q_list) = run_solr_query(param, rows, page, sort != 'score')
(root, search_url, solr_select, q_list) = run_solr_query(param, rows, page, sort)
def do_search(param, sort, page=1, rows=100): (root, search_url, solr_select, q_list) = run_solr_query(param, rows, page, sort != 'score') docs = root.find('result') return web.storage( facet_counts = read_facets(root), docs = docs, is_advanced = bool(param['q']), num_found = (int(docs.attrib['numFound']) if docs is no...
if ':' in q: q = web.urlquote(' '.join(q_list + ['_val_:"sqrt(edition_count)^10"']))
if use_dismax: q = web.urlquote(' '.join(q_list)) solr_select = solr_select_url + "?version=2.2&defType=dismax&q.op=AND&q=%s&qf=text+title^5+author_name^5&bf=sqrt(edition_count)^10&start=%d&rows=%d&fl=key,author_name,author_key,title,subtitle,edition_count,ia,has_fulltext,first_publish_year,cover_edition_key&qt=standar...
def run_solr_query(param = {}, rows=100, page=1, sort=None, spellcheck_count=None): if spellcheck_count == None: spellcheck_count = default_spellcheck_count 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_para...
else: q = web.urlquote(' '.join(q_list)) solr_select = solr_select_url + "?version=2.2&defType=dismax&q.op=AND&q=%s&qf=text+title^0.75+author_name^0.75&bf=sqrt(edition_count)^10&start=%d&rows=%d&fl=key,author_name,author_key,title,subtitle,edition_count,ia,has_fulltext,first_publish_year,cover_edition_key&qt=standard&w...
def run_solr_query(param = {}, rows=100, page=1, sort=None, spellcheck_count=None): if spellcheck_count == None: spellcheck_count = default_spellcheck_count 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_para...
if spellcheck:
if spellcheck is not None and len(spellcheck):
def do_search(param, sort, page=1, rows=100, spellcheck_count=None): (reply, solr_select, q_list) = run_solr_query(param, rows, page, sort, spellcheck_count) 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...
print >> time.asctime(), "no pending seeds. sleeping for 2 seconds."
print >> sys.stderr, time.asctime(), "no pending seeds. sleeping for 2 seconds."
def run(self, configfile): conf = self.read_lists_config(configfile) updater = Updater(conf) while True: seeds = updater.update_pending_seeds(limit=100) if not seeds: print >> time.asctime(), "no pending seeds. sleeping for 2 seconds." time.sleep(2)
meta_fields = self.get_ia_collections()
meta_fields = self.get_ia_meta_fields()
def is_daisy_encrypted(self): meta_fields = self.get_ia_collections() v = meta_fields['collection'] return 'printdisabled' in v or 'lendinglibrary' in v
bot_users = ["/user/EdwardBot", "/user/ImportBot", "/user/WorkBot", "/user/AnandBot", "/user/StatsBot"] where += " AND t.author_id IN (SELECT id FROM thing WHERE key IN $bot_users)"
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)'
"seeds": {"key": self.key}
"seeds": self.get_seed()
def get_lists(self): q = { "type": "/type/list", "seeds": {"key": self.key} } keys = web.ctx.site.things(q) return web.ctx.site.get_many(keys)
public(get_ol_dumps)
def get_ol_dumps(): """Get list of all archive.org items in the in the ol_exports collection uploaded of archive.org staff.""" url = 'http://www.archive.org/advancedsearch.php?q=collection:ol_exports+AND+uploader:(%40archive.org)&fl[]=identifier&output=json' d = simplejson.loads(wget(url)) return sorted(doc['identifie...
if doc.get('has_fulltext', None) == 'true': w['has_fulltext'] = 'true'
if doc.get('has_fulltext', None): w['has_fulltext'] = doc['has_fulltext']
def subjects_covers(path_info): i = web.input(offset=0, limit=12) try: offset = int(i.offset) limit = int(i.limit) except ValueError: return [] (subject_type, key, full_key, q) = read_subject(path_info) 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...
'key': '/works/' + w['key'], 'edition_count': w['edition_count'], 'title': w['title'], 'authors': [{'key': '/authors/' + k, 'name': n} for k, n in zip(w['author_key'], w['author_name'])],
'key': '/works/' + doc['key'], 'edition_count': doc['edition_count'], 'title': doc['title'], 'authors': [{'key': '/authors/' + k, 'name': n} for k, n in zip(doc['author_key'], doc['author_name'])],
def subjects_covers(path_info): i = web.input(offset=0, limit=12) try: offset = int(i.offset) limit = int(i.limit) except ValueError: return [] (subject_type, key, full_key, q) = read_subject(path_info) 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...
re_covers_json = re.compile('^(.+)/covers.json$')
re_covers_json = re.compile('^(.+)/covers$')
def subjects_covers(path_info): i = web.input(offset=0, limit=12) try: offset = int(i.offset) limit = int(i.limit) except ValueError: return [] (subject_type, key, full_key, q) = read_subject(path_info) 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...
return subject_covers(m.group(1))
return subjects_covers(m.group(1))
def GET(self, path_info): m = re_covers_json.match(path_info) if m: return subject_covers(m.group(1)) rows = 12 * 3 offset = 0 if not path_info: return 'subjects page goes here' (subject_type, key, full_key, q) = read_subject(path_info) # q = ' AND '.join('subject_key:"%s"' % url_quote(key.lower().replace('_', ' ')) fo...
assert h.datestr(then, datetime(2010, 1, 1, 0, 0, 0, 10)) == u"just moments ago"
def test_datestr(): from datetime import datetime then = datetime(2010, 1, 1, 0, 0, 0) assert h.datestr(then, datetime(2010, 1, 1, 0, 0, 0, 10)) == u"just moments ago" assert h.datestr(then, datetime(2010, 1, 1, 0, 0, 1)) == u"1 second ago" assert h.datestr(then, datetime(2010, 1, 1, 0, 0, 9)) == u"9 seconds ago" ass...
master_author = web.ctx.site.get(master)
master_author = web.ctx.site.get(master).dict()
def do_merge(self, master, old_keys): master_author = web.ctx.site.get(master) master_author['type']['key'] == '/type/author' edition_keys = set() work_keys = set() updates = [] master_needs_save = False for old in old_keys: q = { 'type': '/type/edition', 'authors': {'key': old}, 'works': None, 'limit': 10000, } editio...
if old_author['name'] not in master_author.setdefault('alternate_names', []):
if old_author.name not in master_author.setdefault('alternate_names', []):
def do_merge(self, master, old_keys): master_author = web.ctx.site.get(master) master_author['type']['key'] == '/type/author' edition_keys = set() work_keys = set() updates = [] master_needs_save = False for old in old_keys: q = { 'type': '/type/edition', 'authors': {'key': old}, 'works': None, 'limit': 10000, } editio...
master_author['alternate_names'].append(old_author['name'])
master_author['alternate_names'].append(old_author.name)
def do_merge(self, master, old_keys): master_author = web.ctx.site.get(master) master_author['type']['key'] == '/type/author' edition_keys = set() work_keys = set() updates = [] master_needs_save = False for old in old_keys: q = { 'type': '/type/edition', 'authors': {'key': old}, 'works': None, 'limit': 10000, } editio...
updates.append(master_author.dict())
updates.append(master_author)
def do_merge(self, master, old_keys): master_author = web.ctx.site.get(master) master_author['type']['key'] == '/type/author' edition_keys = set() work_keys = set() updates = [] master_needs_save = False for old in old_keys: q = { 'type': '/type/edition', 'authors': {'key': old}, 'works': None, 'limit': 10000, } editio...
if doc.get('has_fulltext', None) == 'true': w['has_fulltext'] = 'true'
if w.get('has_fulltext', None) == 'true': i['has_fulltext'] = 'true'
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 doc.get('has_fulltext', None)...
return json.loads(ret)
data = json.loads(ret) if isinstance(data, dict): if 'error' in data: print 'error:' print ret assert 'error' not in data return data
def query(q): url = query_url() + urllib.quote(json.dumps(q)) ret = None for i in range(20): try: ret = urlread(url) while ret.startswith('canceling statement due to statement timeout'): ret = urlread(url) if not ret: print 'ret == None' except IOError: pass if ret: try: return json.loads(ret) except: print ret print u...
return self._request("/api/get_many?" + urllib.urlencode({"keys": simplejson.dumps(keys)}))
response = self._request("/api/get_many?" + urllib.urlencode({"keys": simplejson.dumps(keys)})) return simplejson.loads(response.read())['result']
def _get_many(self, keys): return self._request("/api/get_many?" + urllib.urlencode({"keys": simplejson.dumps(keys)}))
conf = self.read_lists_config(configfile) updater = Updater(conf) self.read_changesets(config['infobase_log_url'], updater.process_changesets) def read_lists_config(self, configfile):
def run(self, configfile, offset_file): self.offset_file = offset_file conf = self.read_lists_config(configfile) updater = Updater(conf) self.read_changesets(config['infobase_log_url'], updater.process_changesets)
return conf.get("lists") def read_log(url, callback, chunksize=100): offset = read_offset(self.offset_file) or default_offset()
updater = Updater(conf.get("lists")) infobase_log_url = "http://%s/openlibrary.org/log" % conf.get("infobase_server") self.read_changesets(infobase_log_url, updater.process_changesets) def read_log(self, url, callback, chunksize=100): offset = self.read_offset(self.offset_file) or self.default_offset()
def read_lists_config(self, configfile): conf = formats.load_yaml(open(configfile).read()) return conf.get("lists")
json = wget("%s/%s?limit=%d" % (url, offset, chunksize))
json = self.wget("%s/%s?limit=%d" % (url, offset, chunksize))
def read_log(url, callback, chunksize=100): offset = read_offset(self.offset_file) or default_offset()
def read_changesets(url, callback, chunksize=100):
def read_changesets(self, url, callback, chunksize=100):
def read_changesets(url, callback, chunksize=100): def f(rows): changesets = [row['data']['changeset'] for row in rows if 'data' in row and 'changeset' in row['data']]
if 'data' in row and 'changeset' in row['data']]
if row.get('data', {}).get('changeset')]
def f(rows): changesets = [row['data']['changeset'] for row in rows if 'data' in row and 'changeset' in row['data']]
self.delete(self.work.key, comment=comment, action="delete")
self.delete(self.work.key, comment=comment)
def save(self, formdata): """Update work and edition documents according to the specified formdata.""" comment = formdata.pop('_comment', '')
return work
return result.docs[0]
def find_matches(self, i): """Tries to find an edition or a work or multiple works that match the given input data. Case#1: No match. None is returned. Case#2: Work match but not editon. Work is returned. Case#3: Work match and edition match. Edition is returned Case#3A: Work match and multiple edition match. List of ...
bad_titles = ['Publications', 'Works. English', 'Works', 'Report', \ 'Letters', 'Calendar', 'Bulletin', 'Plays', \ 'Sermons', 'Correspondence', 'Bill', 'Bills', 'Selections', 'Selected works', 'Selected works. English', 'Laws, etc']
bad_titles = ['Publications', 'Works. English', 'Missal', 'Works', 'Report', \ 'Letters', 'Calendar', 'Bulletin', 'Plays', 'Sermons', 'Correspondence', \ 'Bill', 'Bills', 'Selections', 'Selected works', 'Selected works. English', \ 'The Novels', 'Laws, etc']
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 try: data = get_data(src) except ValueError: print 'bad rec...
q = {'type':'/type/redirect', 'location': str(w['key']), 'limit': 500}
q = {'type':'/type/redirect', 'location': str(w['key']), 'limit': 0}
def find_title_redirects(akey): title_redirects = {} for w in get_existing_works(akey): norm_wt = mk_norm(w['title']) q = {'type':'/type/redirect', 'location': str(w['key']), 'limit': 500} for r in map(get_first_version, ol.query(q)): if mk_norm(r['title']) == norm_wt: continue if r['title'] in title_redirects: assert ...
print 'fix_up_authors'
def fix_up_authors(w, akey, editions): seen_akey = False need_save = False print 'fix_up_authors' for a in w.get('authors', []): print a obj = withKey(a['author']['key']) if obj['type']['key'] == '/type/redirect': a['author']['key'] = obj['location'] a['author']['key'] = '/authors/' + re_author_key.match(a['author']['k...
print a
def fix_up_authors(w, akey, editions): seen_akey = False need_save = False print 'fix_up_authors' for a in w.get('authors', []): print a obj = withKey(a['author']['key']) if obj['type']['key'] == '/type/redirect': a['author']['key'] = obj['location'] a['author']['key'] = '/authors/' + re_author_key.match(a['author']['k...
for ekey in work_to_edition[wkey]:
editions = set(work_to_edition[wkey]) editions.update(e['key'] for e in w['editions']) for ekey in editions:
def update_work_with_best_match(akey, w, work_to_edition, do_updates, fh_log): work_updated = [] best = w['best_match']['key'] update = [] for wkey in w['existing_works'].iterkeys(): if wkey != best: update.append({'type': '/type/redirect', 'location': best, 'key': wkey}) work_updated.append(wkey) for wkey in w['exist...
return read_image(d, size)
try: return read_image(d, size) except IOError: raise web.notfound()
def redirect(id): size_part = size and ("-" + size) or "" url = "/%s/id/%s%s.jpg" % (category, id, size_part) query = web.ctx.env.get('QUERY_STRING') if query: url += '?' + query raise web.found(url)
self.memcache = olmemcache.Client(settings["memcache_servers"]) else: self.memcache = None
self.infobase_conn = connection.MemcacheMiddleware(self.infobase_conn, settings['memcache_servers']) self.infobase_conn = connection.MigrationMiddleware(self.infobase_conn)
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"]) el...
for seed, work, edition, ebook in p.process_edition(e, works)]
for seed, work, edition, ebook in p.process_edition(e, works) if e.get("type", {}).get("key") == "/type/edition" ]
def _index_edition_docs(self, editions, works): """Takes a list of editions and a dict of works of those editions and updates the seed_editions table. """ if not editions: return
docs = self._get_docs_from_memcache(keys) keys2 = [k for k in keys if k not in docs] docs.update(self._get_docs_from_infobase(keys2)) return docs def _get_docs_from_memcache(self, keys): if self.memcache: return self.memcache.get_multi(keys) else: return {} def _get_docs_from_infobase(self, keys):
def _get_docs(self, keys): """Returns docs for the specified keys as a dictionary. """ docs = self._get_docs_from_memcache(keys)
def add_cover_image(key, ia): if has_cover_retry(key): print key, 'has_cover' return
def add_cover_image(ekey, ia): h1 = httplib.HTTPConnection('openlibrary.org') body = json.dumps(dict(username='ImportBot', password=rc['ImportBot'])) headers = {'Content-Type': 'application/json'} h1.request('POST', 'http://openlibrary.org/account/login', body, headers) res = h1.getresponse() res.read() assert res...
def add_cover_image(key, ia): if has_cover_retry(key): print key, 'has_cover' return cover_url = 'http://www.archive.org/download/' + ia + '/page/' + ia + '_preview.jpg' post_data = urllib.urlencode({"url": cover_url}) if key.startswith('/b/'): key = '/books/' + key[3:] ol._request(key + "/add-cover.json", method="POST...
post_data = urllib.urlencode({"url": cover_url}) if key.startswith('/b/'): key = '/books/' + key[3:] ol._request(key + "/add-cover.json", method="POST", data=post_data)
body = urllib.urlencode({"url": cover_url}) assert ekey.startswith('/books/') add_cover_url = 'http://openlibrary.org' + ekey + '/add-cover.json' h1.request('POST', add_cover_url, body, {'Cookie': cookie}) res = h1.getresponse() res.read()
def add_cover_image(key, ia): if has_cover_retry(key): print key, 'has_cover' return cover_url = 'http://www.archive.org/download/' + ia + '/page/' + ia + '_preview.jpg' post_data = urllib.urlencode({"url": cover_url}) if key.startswith('/b/'): key = '/books/' + key[3:] ol._request(key + "/add-cover.json", method="POST...
post(key, ia, ret)
post(ekey, ia, ret)
def add_cover_image(key, ia): if has_cover_retry(key): print key, 'has_cover' return cover_url = 'http://www.archive.org/download/' + ia + '/page/' + ia + '_preview.jpg' post_data = urllib.urlencode({"url": cover_url}) if key.startswith('/b/'): key = '/books/' + key[3:] ol._request(key + "/add-cover.json", method="POST...
q = '%s_key:"%s"' % (subject_type, url_quote(str_to_key(m.group(2)).lower().replace('_', ' ')))
key = str_to_key(m.group(2)).lower().replace('_', ' ') q = '%s_key:"%s"' % (subject_type, url_quote(key))
def GET(self, path_info): rows = 10 offset = 0 if not path_info: return 'subjects page goes here' m = re_subject_types.match(path_info) if m: subject_type = subject_types[m.group(1)] q = '%s_key:"%s"' % (subject_type, url_quote(str_to_key(m.group(2)).lower().replace('_', ' '))) else: subject_type = 'subject' q = 'subje...
q = 'subject_key:"%s"' % url_quote(str_to_key(path_info).lower().replace('_', ' '))
key = str_to_key(path_info).lower().replace('_', ' ') q = 'subject_key:"%s"' % url_quote(key)
def GET(self, path_info): rows = 10 offset = 0 if not path_info: return 'subjects page goes here' m = re_subject_types.match(path_info) if m: subject_type = subject_types[m.group(1)] q = '%s_key:"%s"' % (subject_type, url_quote(str_to_key(m.group(2)).lower().replace('_', ' '))) else: subject_type = 'subject' q = 'subje...
name, count = facets[subject_type + '_facet'][0:2]
def find_name_index (facets, key, subject_type): i = 0 for name, count in web.group(facets[subject_type + '_facet'], 2): if str_to_key(name) == key: return i, name, count i += 1
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'], ia = w.get('ia', []) )
subjects = get_facet('subject_facet', limit=limit+1)[1:]
subjects = [] num == 0 for s in get_facet('subject_facet', limit=limit+1) if num == name_index: continue subjects.append(s) num += 1
def get_subjects(limit=10): if subject_type == 'subject': subjects = get_facet('subject_facet', limit=limit+1)[1:] else: subjects = get_facet('subject_facet', limit=limit) return (web.storage(key='/subjects/' + str_to_key(s).replace(' ', '_'), name=s, count=c) for s, c in subjects)
engine.index_editions(args)
engine.index_editions(keys)
def index_editions(settings_filename, *keys): settings = formats.load_yaml(open(settings_filename).read()) engine = lists.ListsEngine(settings) engine.index_editions(args)
index_editions(args)
index_editions(*args)
def main(cmd=None, *args): if cmd == "index-editions": index_editions(args) elif cmd is None or cmd == "help" or cmd == "--help": print __doc__ else: print >> sys.stderr, "Unknown command %r. see '%s --help'." % (cmd, sys.argv[0])
isbns = doc.get('isbn_10', []) + doc.get('isbn_13')
isbns = doc.get('isbn_10', []) + doc.get('isbn_13', [])
def main(filename): for tokens in read_tsv(filename): json = tokens[-1] doc = simplejson.loads(json) cover = doc.get('covers') and doc.get('covers')[0] isbns = doc.get('isbn_10', []) + doc.get('isbn_13') key = doc['key'] if cover and cover > 0: print "\t".join([cover, key, ",".join(isbns)])
print "\t".join([cover, key, ",".join(isbns)])
print "\t".join([str(cover), key, ",".join(isbns)])
def main(filename): for tokens in read_tsv(filename): json = tokens[-1] doc = simplejson.loads(json) cover = doc.get('covers') and doc.get('covers')[0] isbns = doc.get('isbn_10', []) + doc.get('isbn_13') key = doc['key'] if cover and cover > 0: print "\t".join([cover, key, ",".join(isbns)])
main(sys.argv[1])
import sys main(sys.argv[1])
def main(filename): for tokens in read_tsv(filename): json = tokens[-1] doc = simplejson.loads(json) cover = doc.get('covers') and doc.get('covers')[0] isbns = doc.get('isbn_10', []) + doc.get('isbn_13') key = doc['key'] if cover and cover > 0: print "\t".join([cover, key, ",".join(isbns)])
value = load_translations().ungettext(s1, s2, n)
translations = load_translations(web.ctx.get('lang', 'en')) value = (translations and translations.ungettext(s1, s2, n))
def ungettext(s1, s2, n): value = load_translations().ungettext(s1, s2, n) if value: return value else: # fallback when translation is not provided if n == 1: return s1 else: return s2
def get_seeds(self):
def get_seeds(self, sort=False):
def get_seeds(self): seeds = [Seed(self, s) for s in self.seeds] return h.safesort(seeds, reverse=True, key=lambda seed: seed.last_update)
return h.safesort(seeds, reverse=True, key=lambda seed: seed.last_update)
if sort: seeds = h.safesort(seeds, reverse=True, key=lambda seed: seed.last_update) return seeds
def get_seeds(self): seeds = [Seed(self, s) for s in self.seeds] return h.safesort(seeds, reverse=True, key=lambda seed: seed.last_update)
d = render_template(name).get("messages", {})
d = render_template(template_name).get("messages", {})
def get_message_from_template(template_name, name, *args): d = render_template(name).get("messages", {}) msg = d.get(name) or name.lower().replace("_", " ") if msg and args: return msg % args else: return msg
print 'websafe %r %r' % (text, _websafe(text))
def websafe(text): if isinstance(text, HTML): print 'websafe %r %r' % (text, _websafe(text)) #return _websafe(text.html) return text elif isinstance(text, web.template.TemplateResult): return web.safestr(text) else: return _websafe(text)
print "response", response
def new_start_response(status, headers): response.status = status response.headers = headers if status.startswith("200") and get_response_header("Content-Type", "").startswith("text/"): headers.append(("Content-Encoding", "gzip")) headers.append(("Vary", "Accept-Encoding")) response.compress = True return start_respon...
d = dict((seed, web.storage({"editions": 0, "works": 0, "ebooks": 0, "last_update": ""})) for seed in rawseeds)
zeros = {"editions": 0, "works": 0, "ebooks": 0, "last_update": ""} d = dict((seed, web.storage(zeros)) for seed in rawseeds)
def _get_seed_summary(self): rawseeds = self._get_rawseeds() db = self._get_seeds_db() d = dict((seed, web.storage({"editions": 0, "works": 0, "ebooks": 0, "last_update": ""})) for seed in rawseeds) for row in self._couchdb_view(db, "_all_docs", keys=rawseeds, include_docs=True): if 'doc' in row: d[row.key] = web.st...
d[row.key] = web.storage(row.doc)
if 'edition' not in row.doc: doc = web.storage(zeros, **row.doc) if doc.editions == 0 and row.key.startswith("/books"): doc.editions = 1 d[row.key] = doc
def _get_seed_summary(self): rawseeds = self._get_rawseeds() db = self._get_seeds_db() d = dict((seed, web.storage({"editions": 0, "works": 0, "ebooks": 0, "last_update": ""})) for seed in rawseeds) for row in self._couchdb_view(db, "_all_docs", keys=rawseeds, include_docs=True): if 'doc' in row: d[row.key] = web.st...