<s> from collections import defaultdict <EOL> import json <EOL> import os . path <EOL> import numpy as np <EOL> from vsm . viewer . wrappers import doc_label_name , def_label_fn <EOL> from topicexplorer . lib . hathitrust import parse_marc , get_volume_from_marc <EOL> lda_v = None <EOL> metadata = None <EOL> context_type = None <EOL> class keydefaultdict ( defaultdict ) : <EOL> def __missing__ ( self , key ) : <EOL> if self . default_factory is None : <EOL> raise KeyError ( key ) <EOL> else : <EOL> ret = self [ key ] = self . default_factory ( key ) <EOL> return ret <EOL> ctx_md = keydefaultdict ( lambda ctx : lda_v . corpus . view_metadata ( ctx ) ) <EOL> def init ( viewer , config , args ) : <EOL> global metadata <EOL> global lda_v <EOL> global context_type <EOL> lda_v = viewer <EOL> model_path = config . get ( '<STR_LIT>' , '<STR_LIT:path>' ) <EOL> context_type = config . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> filename = os . path . join ( model_path , '<STR_LIT>' ) <EOL> print "<STR_LIT>" , filename <EOL> with open ( filename ) as f : <EOL> metadata = json . load ( f ) <EOL> def label ( doc ) : <EOL> if context_type == '<STR_LIT>' : <EOL> try : <EOL> md = metadata [ doc ] <EOL> return md [ '<STR_LIT:title>' ] [ <NUM_LIT:0> ] <EOL> except : <EOL> return doc <EOL> elif context_type == '<STR_LIT>' : <EOL> context_md = ctx_md [ '<STR_LIT>' ] <EOL> where = np . squeeze ( np . where ( np . in1d ( context_md [ '<STR_LIT>' ] , [ doc ] ) ) ) <EOL> page_no = context_md [ '<STR_LIT:file>' ] [ where ] <EOL> page_no = page_no . split ( '<STR_LIT:/>' ) [ - <NUM_LIT:1> ] <EOL> page_no = page_no . replace ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> page_no = int ( page_no ) <EOL> book_label = context_md [ '<STR_LIT>' ] [ where ] <EOL> md = metadata [ book_label ] <EOL> try : <EOL> xml = parse_marc ( md [ '<STR_LIT>' ] . encode ( '<STR_LIT:utf8>' ) ) <EOL> vol = get_volume_from_marc ( xml [ <NUM_LIT:0> ] ) <EOL> return "<STR_LIT>" % ( page_no , vol , md [ '<STR_LIT:title>' ] [ <NUM_LIT:0> ] ) <EOL> except : <EOL> pass <EOL> try : <EOL> return "<STR_LIT>" % ( page_no , md [ '<STR_LIT:title>' ] [ <NUM_LIT:0> ] ) <EOL> except : <EOL> return doc <EOL> def id_fn ( md ) : <EOL> context_md = lda_v . corpus . view_metadata ( context_type ) <EOL> ctx_label = doc_label_name ( context_type ) <EOL> return context_md [ ctx_label ] </s>
