Ejemplo n.º 1
0
def __get_featured_instances__(featured_instances=FEATURED_INSTANCES):
    "Helper function iterates through featured instances returns list"
    output = []
    for instance_key in featured_instances:
        cover_art_key = None
        instance_link = '/apps/discovery/Instance/{0}'.format(
            instance_key.split(":")[-1])
        for annotation_key in REDIS_DATASTORE.smembers(
            '{0}:hasAnnotation'.format(instance_key)):
            if annotation_key.startswith('bf:CoverArt'):
                cover_art_key = annotation_key
        work_key = REDIS_DATASTORE.hget(instance_key,
                                       'instanceOf')
        cover_id = cover_art_key.split(":")[-1]
        cover_url = '/apps/discovery/CoverArt/{0}-'.format(cover_id)
        if REDIS_DATASTORE.hexists(cover_art_key, 'annotationBody'):
            cover_url += "body.jpg"
        else:
            cover_url += 'thumbnail.jpg'
        output.append(
            {'cover': cover_url,
             'title': REDIS_DATASTORE.hget(
                '{0}:title'.format(work_key),
                'rda:preferredTitleForTheWork'),
             'instance': instance_link})
    return output
def display_brief(work):
    "Returns CC version of a Brief summary based on White While DL design"
    work_template = template.loader.get_template(
        'cc-brief.html')
    title_entity = REDIS_DATASTORE.hget(work.title, 'label')
    if REDIS_DATASTORE.hexists(work.redis_key, "rda:isCreatedBy"):
        creators_keys = [REDIS_DATASTORE.hget(work.redis_key,
                                         "rda:isCreatedBy"),]
    else:
        creators_keys = list(REDIS_DATASTORE.smembers(
            "{0}:rda:isCreatedBy".format(work.redis_key)))
    creators = []
    for redis_key in creators_keys[:4]:
        creator = {'id': redis_key.split(":")[-1]}
        given_name = REDIS_DATASTORE.hget(redis_key, 'schema:givenName')
        if given_name is not None:
            creator['givenName'] = unicode(given_name, errors='ignore')
        family_name = REDIS_DATASTORE.hget(redis_key, 'schema:familyName')
        if family_name is not None:
            creator['familyName'] = unicode(family_name, errors='ignore')
        creator['name'] = unicode(REDIS_DATASTORE.hget(redis_key,
                                  'rda:preferredNameForThePerson'),
                                  errors='ignore')
        creators.append(creator)
        
                         
    context = template.Context({'creators': creators,
                                'title': title_entity,
                                'work': work}
                                )
    return mark_safe(work_template.render(context))
Ejemplo n.º 3
0
def location_facet(request, name):
    rlsp_query_key = request.session.get('rlsp-query', None)
    location_key = REDIS_DATASTORE.hget('carl-prospector-slug-names', name)
    if not location_key:
        raise Http404
    result = REDIS_DATASTORE.sinter(rlsp_query_key,
                                    '{0}:resourceRole:own'.format(location_key))
    records = []
    for instance_key in result:
        work_key = REDIS_DATASTORE.hget(instance_key, 'instanceOf')
        work_classname = work_key.split(":")[1]
        work_class = getattr(bibframe.models,
                             work_classname)
        records.append(work_class(redis_datastore=REDIS_DATASTORE,
                                  redis_key=work_key))
    msg = "{0} Results for {1} owned by {2}".format(
        len(records),
        request.session.get('q', None),
        REDIS_DATASTORE.hget(location_key, 'label'))
    return render(request,
                  'discovery/app.html',
                              {'app': APP,
                               'example':{},
                               'feedback_form':FeedbackForm({'subject':'Discovery Facet Display'}),
                               'feedback_context':request.get_full_path(),
                               'institution': INSTITUTION,
                               'facet_list': None,
                               'message': msg,
                               'pagination':None,
                               'results':records,
                               'search_form': SearchForm(),
                               'search_query': None,
                               'user': None})    
Ejemplo n.º 4
0
def display_collection(placeholder):
    output = ""
    for i in range(1, int(REDIS_DATASTORE.get('global bf:Manuscript'))):
        work_key = 'bf:Manuscript:{0}'.format(i)
        title_key = REDIS_DATASTORE.hget(work_key, 'title')
        instance_key = REDIS_DATASTORE.hget(work_key, 'hasInstance')
        title = REDIS_DATASTORE.hget(title_key, 'titleValue')
        pdf_location = REDIS_DATASTORE.hget(instance_key, 'schema:contentUrl')
        output += """<li><a href="/apps/discovery/Manuscript/{0}">{1}</a>
<a href="{2}"><img src="/static/img/pdficon_small.png"></a></li>
""".format(i, title, pdf_location)
    return mark_safe(output)
def display_collection(placeholder):
    output = ""
    for i in range(1, int(REDIS_DATASTORE.get('global bf:Manuscript'))):
        work_key = 'bf:Manuscript:{0}'.format(i)
        title_key = REDIS_DATASTORE.hget(work_key, 'title')
        instance_key = REDIS_DATASTORE.hget(work_key, 'hasInstance')
        title = REDIS_DATASTORE.hget(title_key, 'titleValue')
        pdf_location = REDIS_DATASTORE.hget(instance_key,
                                            'schema:contentUrl')
        output += """<li><a href="/apps/discovery/Manuscript/{0}">{1}</a>
<a href="{2}"><img src="/static/img/pdficon_small.png"></a></li>
""".format(i, title, pdf_location)
    return mark_safe(output)
def get_prospector_data(app=None):
    "Returns Google Charts string of Prospector Holdings"
    # update_institution_count()
    js_str = ''
    #! THIS OPERATION SHOULD BE CACHED
    for row in  REDIS_DATASTORE.zrevrange('prospector-holdings',
                                          0,
                                          -1,
                                          withscores=True):
        org_key = row[0]
        if int(row[1]) < 1:
            continue
        library_info = [REDIS_DATASTORE.hget(org_key, 'label'),
                        REDIS_DATASTORE.scard(
                            "{0}:bf:Books".format(org_key)),
                        REDIS_DATASTORE.scard(
                            "{0}:bf:MovingImage".format(org_key)),
                        REDIS_DATASTORE.scard(
                            "{0}:bf:MusicalAudio".format(org_key)),
                        row[1] # Total Holdings
                        ]
        js_str += '["{0}",{1}],\n'.format(library_info[0],
                                          ','.join([str(i)
                                                    for i in library_info[1:]]))
    js_str = js_str[:-2] # Removes trailing comma
    return mark_safe(js_str)
def author_of(person):
    "Returns div with a list of Works that the person is an author of"
    author_role_key = "{0}:resourceRole:aut".format(person.redis_key)
    if not REDIS_DATASTORE.exists(author_role_key):
        return mark_safe('')
    author_html = """<div class="alert alert-info alert-block">
    <h3>Author's Creative Works</h3><ul>"""
    for work_key in REDIS_DATASTORE.smembers(author_role_key):
        work_info = work_key.split(":")
        title_key = REDIS_DATASTORE.hget(work_key, 'title')
        title = REDIS_DATASTORE.hget(title_key, 'label')
        author_html += """<li>{0} <em><a href="/apps/discovery/{0}/{1}">{2}</a></li></em>
         """.format(work_info[1],
                    work_info[-1],
                    title)
    author_html += "</ul></div>"
    return mark_safe(author_html)
Ejemplo n.º 8
0
def get_subjects(creative_work):
    work_key = creative_work.redis_key
    output = ""
    subject_work_key = "{0}:subject".format(work_key)
    if REDIS_DATASTORE.exists(subject_work_key):
        for topic_key in REDIS_DATASTORE.smembers(subject_work_key):
            topic_id = topic_key.split(":")[-1]
            label = REDIS_DATASTORE.hget(topic_key, 'label')
            output += """<li><a href="/apps/discovery/Topic/{0}">{1}</a>
            </li>
""".format(topic_id, label)
    else:
        topic_key = REDIS_DATASTORE.hget(work_key, 'subject')
        topic_id = topic_key.split(":")[-1]
        label = REDIS_DATASTORE.hget(topic_key, 'label')
        output += """<li><a href="/apps/discovery/Topic/{0}">{1}</a></li>
""".format(topic_id, label)
    return mark_safe(output)
def get_subjects(creative_work):
    work_key = creative_work.redis_key
    output = ""
    subject_work_key = "{0}:subject".format(work_key)
    if REDIS_DATASTORE.exists(subject_work_key):
        for topic_key in REDIS_DATASTORE.smembers(
            subject_work_key):
            topic_id = topic_key.split(":")[-1]
            label = REDIS_DATASTORE.hget(topic_key, 'label')
            output += """<li><a href="/apps/discovery/Topic/{0}">{1}</a>
            </li>
""".format(topic_id, label)
    else:
        topic_key = REDIS_DATASTORE.hget(work_key, 'subject')
        topic_id = topic_key.split(":")[-1]
        label = REDIS_DATASTORE.hget(topic_key, 'label')
        output += """<li><a href="/apps/discovery/Topic/{0}">{1}</a></li>
""".format(topic_id, label)
    return mark_safe(output)
Ejemplo n.º 10
0
def setup_seed_rec():
    """
    Helper function returns a record based on the SEED_RECORD_ID
    for the default view
    """
    if REDIS_DATASTORE.hexists(SEED_RECORD_ID,'callno-lcc'):
        lcc = REDIS_DATASTORE.hget(SEED_RECORD_ID,'callno-lcc')
        current = redis_helpers.get_record(call_number=lcc)
        return current
    else:
        return None
Ejemplo n.º 11
0
def bibframe_by_name(request, class_name, slug):
    """Displays either a disambiguation of multiple BIBFRAME entities
    that match the slugified title or a single BIBFRAME entity otherwise.

    Parameters:
    class_name -- BIBFRAME Class
    slug -- Title of BIBFRAME entity as a slug
    """
    title_key = REDIS_DATASTORE.hget('title-slugs-hash', slug)
    if title_key is None:
        raise Http404
    return HttpResponse("{0} {1}".format(class_name, title_key))
def get_creators(bibframe_entity):
    output = '<ul class="icons-ul">'
    if type(bibframe_entity) == Instance:
        redis_key = bibframe_entity.attributes.get('instanceOf')
    else:
        redis_key = bibframe_entity.redis_key
    if REDIS_DATASTORE.hexists(redis_key,"rda:isCreatedBy"):
        creators = [REDIS_DATASTORE.hget(redis_key,"rda:isCreatedBy"),]
    else:
        creators = list(REDIS_DATASTORE.smembers("{0}:rda:isCreatedBy".format(redis_key)))
        
    
    for i, key in enumerate(creators):
        creator_id = key.split(":")[-1]
        output += """<li><a href="/apps/discovery/Person/{0}">
<i class="icon-li icon-user"></i> {1}</a></li>""".format(
        key.split(":")[-1],
        REDIS_DATASTORE.hget(key,
                             'rda:preferredNameForThePerson'))
    output += "</ul>"
    return mark_safe(output)
Ejemplo n.º 13
0
def display_cover_image(request, redis_id, type_of, image_ext):
    """
    Returns a cover image based on the CoverArt's redis key,
    if the type-of is body or thumbnail and the image_ext is
    either "jpg", "png", or "gif"
    
    :param redis_id: Redis key id of the bibframe:CoverArt 
    :param type_of: Should be either "thumbnail" or "body" 
    "param image_ext: The images extension
    """
    redis_key = "bf:CoverArt:{0}".format(redis_id)
    if type_of == 'thumbnail':
        raw_image = REDIS_DATASTORE.hget(redis_key, 
                                          'thumbnail')
    elif type_of == 'body':
        raw_image = REDIS_DATASTORE.hget(redis_key, 
                                          'annotationBody')
    if raw_image is None:
        raise Http404
    return HttpResponse(raw_image, 
                        mimetype="image/{0}".format(image_ext))
Ejemplo n.º 14
0
def get_brief_view(work_key):
    work_template = template.loader.get_template('work-brief-view.html')
    work = {
        'url':
        '/apps/discovery/Manuscript/{0}'.format(work_key.split(":")[-1])
    }
    instance_key = REDIS_DATASTORE.hget(work_key, 'hasInstance')
    title_key = REDIS_DATASTORE.hget(work_key, 'title')
    work['title'] = REDIS_DATASTORE.hget(title_key, 'label')
    work['pdf_url'] = REDIS_DATASTORE.hget(instance_key, 'schema:contentUrl')
    work['topics'] = []
    topic_keys = []
    if REDIS_DATASTORE.hexists(work_key, 'subject'):
        topic_key = REDIS_DATASTORE.hget(work_key, 'subject')
        topic_keys.append(topic_key)
    else:
        topic_keys.extend(
            list(REDIS_DATASTORE.smembers('{0}:subject'.format(work_key))))
    for topic_key in topic_keys:
        work['topics'].append({
            'label':
            REDIS_DATASTORE.hget(topic_key, 'label'),
            'url':
            '/apps/discovery/Topic/{0}'.format(topic_key.split(":")[-1])
        })
    return mark_safe(work_template.render(template.Context({'work': work})))
Ejemplo n.º 15
0
def display_topic_cloud(placeholder):
    topics = []
    for i in range(1, int(REDIS_DATASTORE.get('global bf:Topic'))):
        topic_key = 'bf:Topic:{0}'.format(i)
        topic_works_key = '{0}:works'.format(topic_key)
        total_works = int(REDIS_DATASTORE.scard(topic_works_key))
        if total_works < 3:
            topic_size = 12
        elif total_works < 10:
            topic_size = 16
        else:
            topic_size = total_works
        topics.append("""<a style="font-size: {0}px"
href="/apps/discovery/Topic/{1}">{2}</a>""".format(
            topic_size, i, REDIS_DATASTORE.hget(topic_key, 'label')))
    return mark_safe(", ".join(topics))
Ejemplo n.º 16
0
def about_work(work):
    "Filter extracts and renders a DL html list of a bf:Work or subclasses"
    about_work_template = template.loader.get_template('about-work-dl.html')
    work_properties = []
    pub_date = getattr(work, 'rda:dateOfPublicationManifestation')
    if pub_date is not None:
        work_properties.append({'name': 'Publication Date', 'value': pub_date})
    lcc_class = getattr(work, 'class-lcc')
    if lcc_class is not None:
        work_properties.append({'name': 'LCC Class', 'value': lcc_class})
    instance_key = work.hasInstance
    carrier_type = REDIS_DATASTORE.hget(instance_key,
                                        'rda:carrierTypeManifestation')
    work_properties.append({'name': 'Format', 'value': carrier_type})
    work_properties.sort(key=lambda prop: prop.get('name'))
    return mark_safe(
        about_work_template.render(
            template.Context({'work_properties': work_properties})))
def display_topic_cloud(placeholder):
    topics = []
    for i in range(1, int(REDIS_DATASTORE.get('global bf:Topic'))):
        topic_key = 'bf:Topic:{0}'.format(i)
        topic_works_key = '{0}:works'.format(topic_key)
        total_works = int(REDIS_DATASTORE.scard(topic_works_key))
        if total_works < 3:
            topic_size = 12
        elif total_works < 10:
            topic_size = 16
        else:
            topic_size = total_works
        topics.append("""<a style="font-size: {0}px"
href="/apps/discovery/Topic/{1}">{2}</a>""".format(
    topic_size,
    i,
    REDIS_DATASTORE.hget(topic_key, 'label')))
    return mark_safe(", ".join(topics))
def display_instances(work):
    "Generates a display of all of the instances for a work"
    work_instances_template = template.loader.get_template(
        'cc-work-instances.html')
    instances = []
    instance_keys = list(REDIS_DATASTORE.smembers(
        "{0}:hasInstance".format(work.redis_key)))
    if len(instance_keys) < 1:
        instance_key = REDIS_DATASTORE.hget(work.redis_key,
                                             'hasInstance')
        if instance_key is not None:
            instance_keys.append(instance_key)
                
    for instance_key in instance_keys:
        instances.append(
            Instance(redis_key=instance_key,
                     redis_datastore=REDIS_DATASTORE))
    context =  template.Context({'instances': instances})
    return mark_safe(work_instances_template.render(context))
def get_prospector_bar_chart(app=None):
    "Returns a javascript for a Canvas.js bar chart of Prospector Holdings"
    js_str = "var ctx=$('#prospector-rlsp-bar').get(0).getContext('2d');"
    data = {'labels':[],
            'data':[]}
    for row in  REDIS_DATASTORE.zrevrange('prospector-holdings',
                                          0,
                                          -1,
                                          withscores=True):
        if float(row[1]) > 0:
            org_key = row[0]
            data['labels'].append(REDIS_DATASTORE.hget(org_key, 'label'))
            data['data'].append(str(row[1]))
    js_str += """var data={{ labels: ["{0}"],""".format('","'.join(data['labels']))
    js_str += """datasets: [ {{ fillColor : "rgba(151,187,205,0.5)",
                               strokeColor : "rgba(151,187,205,1)",
                               data : [{0}]}}]}};""".format(','.join(data['data']))
    js_str += "new Chart(ctx).Bar(data, {scaleShowLabel: true});"
    return mark_safe(js_str)
Ejemplo n.º 20
0
def feedback(request):
    """
    Feedback view for the Aristotle Library Apps Project

    :param request: Web request from client
    """
    if request.method != 'POST':
        return Http404
    today = datetime.datetime.utcnow()
    feedback_id = REDIS_DATASTORE.incr(
        "global feedback:{0}:{1}".format(today.year,
                                         today.month))
    feedback_key = "feedback:{0}:{1}:{2}".format(today.year, 
		                                 today.month, 
						 feedback_id)
    REDIS_DATASTORE.hset(feedback_key, "created", today.isoformat())
    REDIS_DATASTORE.hset(feedback_key, "comment", request.POST.get('comment'))
    REDIS_DATASTORE.hset(feedback_key, "context", request.POST.get('context'))
    if request.POST.has_key('sender'):
        REDIS_DATASTORE.hset(feedback_key, "sender", request.POST.get('sender'))
    
    return redirect(REDIS_DATASTORE.hget(feedback_key, "context"))
def about_work(work):
    "Filter extracts and renders a DL html list of a bf:Work or subclasses"
    about_work_template = template.loader.get_template('about-work-dl.html')
    work_properties = []
    pub_date = getattr(work, 'rda:dateOfPublicationManifestation')
    if pub_date is not None:
        work_properties.append({'name': 'Publication Date',
                                'value': pub_date})
    lcc_class = getattr(work,
                        'class-lcc')
    if lcc_class is not None:
        work_properties.append({'name': 'LCC Class',
                                'value': lcc_class})
    instance_key = work.hasInstance
    carrier_type = REDIS_DATASTORE.hget(instance_key,
                                        'rda:carrierTypeManifestation')
    work_properties.append({'name': 'Format',
                            'value': carrier_type})
    work_properties.sort(key=lambda prop: prop.get('name'))
    return mark_safe(
        about_work_template.render(
            template.Context({'work_properties': work_properties})))
def get_brief_view(work_key):
    work_template = template.loader.get_template('work-brief-view.html')
    work = {
        'url': '/apps/discovery/Manuscript/{0}'.format(work_key.split(":")[-1])}
    instance_key = REDIS_DATASTORE.hget(work_key, 'hasInstance')
    title_key = REDIS_DATASTORE.hget(work_key, 'title')
    work['title'] = REDIS_DATASTORE.hget(title_key, 'label')
    work['pdf_url'] = REDIS_DATASTORE.hget(instance_key, 'schema:contentUrl')
    work['topics'] = []
    topic_keys = []
    if REDIS_DATASTORE.hexists(work_key, 'subject'):
        topic_key = REDIS_DATASTORE.hget(work_key, 'subject')
        topic_keys.append(topic_key)
    else:
        topic_keys.extend(list(REDIS_DATASTORE.smembers(
            '{0}:subject'.format(work_key))))
    for topic_key in topic_keys:
        work['topics'].append(
        {'label': REDIS_DATASTORE.hget(topic_key, 'label'),
         'url': '/apps/discovery/Topic/{0}'.format(
             topic_key.split(":")[-1])})
    return mark_safe(
        work_template.render(
            template.Context({'work': work})))
Ejemplo n.º 23
0
 def sort_func(work_key):
     title_key = REDIS_DATASTORE.hget(work_key, 'title')
     return REDIS_DATASTORE.hget(title_key, 'label')
def enhance_with_google_book(instance_key):
    """Function takes an id name, value, and enhances BIBFRAME entities.
     
    Keywords:
    instance -- BIBFRAME Instance
    """
    params = {'key': GOOGLE_API_KEY}
    for id_name in ['isbn', 'issn']:
        id_value = REDIS_DATASTORE.hget(instance_key, id_name)
        if id_value is not None:
            params['q'] = '{0}:{1}'.format(id_name,
                                           id_value)
            break
    if params.has_key('q'):
        goog_url = 'https://www.googleapis.com/books/v1/volumes?{0}'.format(
            urllib.urlencode(params))
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
        opener.addheaders = [('User-Agent',
                              'Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')]
        book_json = json.load(urllib2.urlopen(goog_url))
        if book_json.has_key('items'):
            for item in book_json['items']:
                dateOfAssertion=datetime.datetime.utcnow()
                # Create a Google Books Description of the Instance
                google_desc = Description(annotates=instance_key,
                                          annotationSource=item["volumeInfo"]["infoLink"],
                                          dateOfAssertion=dateOfAssertion.isoformat(),
                                          label="Google Description of {0}".format(
                                              item['volumeInfo'].get('title')),
                                          redis_datastore=REDIS_DATASTORE)
                setattr(google_desc,
                        'prov:generated',
                        goog_url)
                google_desc.save()
                REDIS_DATASTORE.sadd(
                    '{0}:hasAnnotation'.format(instance_key),
                    google_desc.redis_key)
                if item['volumeInfo'].has_key('imageLinks'):
                    new_cover = CoverArt(annotates=instance_key,
                                         dateOfAssertion=dateOfAssertion.isoformat(),
                                         redis_datastore=REDIS_DATASTORE)
                    setattr(new_cover,
                            'prov:generated',
                            goog_url)
                    if item['volumeInfo']['imageLinks'].has_key('smallThumbnail'):
                        img_url = item['volumeInfo']['imageLinks']['smallThumbnail']
                        request = urllib2.Request(img_url)
                        data = opener.open(request).read()
                        setattr(new_cover,
                                'thumbnail',
                                data)
                    if item['volumeInfo']['imageLinks'].has_key('thumbnail'):
                        img_url = item['volumeInfo']['imageLinks']['thumbnail']
                        request = urllib2.Request(img_url)
                        data = opener.open(request).read()
                        setattr(new_cover,
                                'annotationBody',
                                data)
                    new_cover.save()
                    REDIS_DATASTORE.sadd(
                        '{0}:hasAnnotation'.format(instance_key),
                        new_cover.redis_key)
Ejemplo n.º 25
0
def get_pdf_uri(creative_work):
    return mark_safe(
        REDIS_DATASTORE.hget(creative_work.hasInstance, 'schema:contentUrl'))
def get_pdf_uri(creative_work):
    return mark_safe(REDIS_DATASTORE.hget(creative_work.hasInstance,
                                          'schema:contentUrl'))
def ingest_fedora(parent_pid, work_classname):
    """Function ingests a collection of Fedora Commons objects into the
    BIBFRAME Redis datastore

    Parameters:
    parent_pid -- PID of Parent Collection
    work_classname -- class name of the work
    """
    collection_sparql = """PREFIX fedora: <info:fedora/fedora-system:def/relations-external#>
SELECT ?a FROM <#ri> WHERE {
   ?a <info:fedora/fedora-system:def/relations-external#isMemberOfCollection>"""
    collection_sparql += "<info:fedora/{0}>".format(parent_pid) +  "}"
    if work_classname is None:
        ingester = MODSIngester(redis_datastore=REDIS_DATASTORE)
    else:
        ingester = MODSIngester(redis_datastore=REDIS_DATASTORE,
                                work_class=getattr(bibframe.models,
                                                   work_classname))
    csv_reader = FEDORA_REPO.risearch.sparql_query(collection_sparql)
    collection_pids = []
    for row in csv_reader:
        full_pid = row.get('a')
        collection_pids.append(full_pid.split("/")[-1])
    start_time = datetime.datetime.utcnow()
    sys.stderr.write("Started Fedora Commons Object Ingestion at {0}\n".format(
        start_time.isoformat()))
    for pid in collection_pids:
        repo_mods_result = FEDORA_REPO.api.getDatastreamDissemination(
            pid=pid,
            dsID="MODS")
        ingester.instances = []
        ingester.mods_xml = etree.XML(repo_mods_result[0])
        ingester.__ingest__()
        try:
            thumbnail_result = FEDORA_REPO.api.getDatastreamDissemination(
                pid=pid,
                dsID="TN")
        except RequestFailed:
            thumbnail_result = None
        org_key = REDIS_DATASTORE.hget(PREFIX_HASH_KEY,
                                       pid.split(":")[0])
        if org_key is None:
            raise ValueError("Must have an org key for {0}".format(pid))
        for instance_key in ingester.instances:
            if thumbnail_result is not None:
                new_cover = CoverArt(redis_datastore=REDIS_DATASTORE,
                                     annotates=instance_key)
                setattr(new_cover,
                        'prov:generated',
                        FEDORA_URI)
                setattr(new_cover,
                        'thumbnail',
                        thumbnail_result[0])
                new_cover.save()
                REDIS_DATASTORE.sadd('{0}:hasAnnotation'.format(instance_key),
                                     new_cover.redis_key)
            if org_key is not None:
                REDIS_DATASTORE.sadd('{0}:resourceRole:own'.format(org_key),
                                     instance_key)
        print("\tFinished ingestion {0}".format(pid))
    
                
                
                
            
            
    
    
    end_time = datetime.datetime.utcnow()
    sys.stderr.write("Finished Fedora Commons Object Ingestion at {0} ".format(
        end_time.isoformat()))
    sys.stderr.write("Total Objects processed={0} time={1} minutes".format(
        len(collection_pids),
        (end_time-start_time).seconds / 60.0))
Ejemplo n.º 28
0
def facet_detail(request, facet_name, facet_item):
    """Displays a specific Facet listing

    Parameters:
    facet_name -- Name of the Facet
    facet_item -- Name of the Facet item
    """
    redis_key = "bf:Facet:{0}:{1}".format(facet_name,facet_item)
    if not REDIS_DATASTORE.exists(redis_key):
        raise Http404
    rlsp_query_key = request.session.get('rlsp-query', None)
    listing_key = "facet-listing:{0}:{1}".format(facet_name,facet_item)
    if rlsp_query_key is not None:
        tmp_facet_result = 'facet-result:{0}'.format(
            REDIS_DATASTORE.incr('global facet-result'))
        REDIS_DATASTORE.sinterstore(tmp_facet_result,
                                    rlsp_query_key,
                                    redis_key)
        REDIS_DATASTORE.expire(tmp_facet_result, 900)
        REDIS_DATASTORE.sort(tmp_facet_result,
                             alpha=True,
                             store=listing_key)
    else:

        REDIS_DATASTORE.sort(redis_key,
                             alpha=True,
                             store=listing_key)
    REDIS_DATASTORE.expire(listing_key,1200)
    offset =  int(request.REQUEST.get('offset',0))
    records = []
    pagination = get_pagination(request.path,
                                listing_key,
                                REDIS_DATASTORE,
                                offset)
    record_slice = REDIS_DATASTORE.lrange(listing_key,
                                          offset,
                                          offset+PAGINATION_SIZE)
    for row in record_slice:
        if row.find("Instance") > -1:
            work_key = REDIS_DATASTORE.hget(row, 'instanceOf')
        entity_name = work_key.split(":")[1]
        if CREATIVE_WORK_CLASSES.count(entity_name) > 0:
            cw_class = getattr(bibframe.models,
                               entity_name)
            if cw_class is None:
                cw_class = getattr(bibframe.models,
                                   entity_name.title())
            work = cw_class(
                redis_datastore=REDIS_DATASTORE,
                redis_key=work_key)
            records.append(work)
    label_key = 'bf:Facet:{0}s'.format(facet_name)
    msg = "Results {0} of {1} for Facet {2}".format(len(record_slice),
                                                    REDIS_DATASTORE.llen(listing_key),
                                                    facet_name)
    if REDIS_DATASTORE.exists(label_key):
        if REDIS_DATASTORE.type(label_key) == 'zset':
            msg = "{0} {1}".format(msg, facet_item)
        else:
            msg = " {0} {1}".format(msg,    
                                    REDIS_DATASTORE.hget(label_key, facet_item))
    else:
        msg = "{0} of {1}".format(msg, facet_item)
    return render(request,
                  'discovery/app.html',
                  {'app': APP,
                   'example':{},
                   'feedback_form':FeedbackForm({'subject':'Discovery Facet Display'}),
                   'feedback_context':request.get_full_path(),
                   'institution': INSTITUTION,
                   'facet_list': None,
                   'message': msg,
                   'pagination':None,
                   'results': records,
                   'search_form': SearchForm(),
                   'search_query': None,
                   'user': None})

                              

    return HttpResponse("In facet detail key={0}\n{1}".format(redis_key,records))