# -*- coding: utf-8 -*- """Build the card-pool index used to find comparable cards for the TRK review.""" import gzip, json, re, math, os, pickle from collections import defaultdict, Counter BASE = os.path.dirname(os.path.abspath(__file__)) POOL_GZ = os.path.join(BASE, '..', '..', '.tmp', 'oracle.jsonl.gz') STOP = set("""a an the of to and or if you your it its this that they their them he she his her him we our us i me my mine is are was were be been being do does did would could should can may might will shall not no than then when whenever as at by for from in into on onto out up with without each other another any all one two three four five six seven eight nine ten x y z card cards spell spells permanent permanents player players opponent opponents creature creatures artifact artifacts enchantment enchantments land lands instant sorcery battle planeswalker token tokens put puts putting get gets gotten gain gains lose loses losing control controls target targets choose chosen instead also only more less equal number source """.split()) def norm_text(t): if not t: return '' t = t.replace('\u2014', '-').replace('\u2019', "'") # strip reminder text (parentheses), but keep keyword names t = re.sub(r'\([^)]*\)', ' ', t) t = t.lower() t = re.sub(r'\{[^}]*\}', ' ', t) # mana symbols t = re.sub(r'[^a-z0-9+\-/ ]', ' ', t) t = re.sub(r'\s+', ' ', t).strip() return t def tokens(c): text = norm_text(c.get('oracle_text', '')) tl = norm_text(c.get('type_line', '')) words = [w for w in text.split() if w not in STOP and len(w) > 1] toks = list(words) toks += [a + '_' + b for a, b in zip(words, words[1:])] toks += ['TYPE_' + w for w in tl.split() if w not in STOP] for kw in c.get('keywords') or []: toks.append('KW_' + norm_text(kw).replace(' ', '_')) return toks TYPE_CAT = { 'creature': 'creature', 'artifact': 'artifact', 'enchantment': 'enchantment', 'instant': 'instant', 'sorcery': 'sorcery', 'land': 'land', 'planeswalker': 'planeswalker', 'battle': 'battle', } def type_cat(c): tl = (c.get('type_line') or '').lower() # creature dominates for artifact creatures if 'creature' in tl: return 'creature' if 'land' in tl: return 'land' for k, v in TYPE_CAT.items(): if k in tl: return v return 'other' def load_pool(): pool = [] with gzip.open(POOL_GZ, 'rt', encoding='utf-8') as f: for line in f: c = json.loads(line) if c.get('set') == 'trk' and not c.get('reprint'): continue if c.get('layout') in ('token', 'emblem', 'art_series', 'double_faced_token', 'planar', 'scheme', 'vanguard'): continue if c.get('type_line', '').startswith(('Token', 'Emblem', 'Card //', 'Card')): continue if not c.get('oracle_text') and not c.get('keywords'): # vanilla creatures still useful for stats, keep pass pool.append({ 'name': c['name'], 'rarity': c.get('rarity'), 'mana_cost': c.get('mana_cost', ''), 'cmc': c.get('cmc') or 0, 'type_line': c.get('type_line', ''), 'type_cat': type_cat(c), 'oracle_text': c.get('oracle_text', ''), 'colors': c.get('colors') or [], 'power': c.get('power'), 'toughness': c.get('toughness'), 'keywords': c.get('keywords') or [], 'set': c.get('set'), 'released_at': c.get('released_at', ''), 'legalities': c.get('legalities') or {}, 'edhrec_rank': c.get('edhrec_rank'), }) return pool def build_index(pool): df = Counter() docs = [] for c in pool: tf = Counter(tokens(c)) docs.append(tf) for t in tf: df[t] += 1 N = len(pool) idf = {t: math.log((N + 1) / (n + 1)) + 1 for t, n in df.items()} postings = defaultdict(list) norms = [0.0] * N for i, tf in enumerate(docs): s = 0.0 for t, n in tf.items(): w = (1 + math.log(n)) * idf.get(t, 0) postings[t].append((i, w)) s += w * w norms[i] = math.sqrt(s) or 1.0 return {'postings': postings, 'idf': idf, 'norms': norms, 'pool': pool, 'N': N} def search(idx, card, topk=40): tf = Counter(tokens(card)) scores = defaultdict(float) cm = (card.get('cmc') or 0) cc = type_cat(card) cc_colors = set(card.get('colors') or []) for t, n in tf.items(): w = (1 + math.log(n)) * idx['idf'].get(t, 0) if not w: continue for i, pw in idx['postings'].get(t, ()): scores[i] += w * pw pool = idx['pool'] res = [] for i, s in scores.items(): c = pool[i] s = s / idx['norms'][i] if c['type_cat'] == cc: s += 0.10 if abs((c['cmc'] or 0) - cm) <= 1: s += 0.05 if set(c['colors']) == cc_colors: s += 0.05 res.append((s, c)) res.sort(key=lambda x: -x[0]) return res[:topk] if __name__ == '__main__': pool = load_pool() print('pool cards', len(pool)) idx = build_index(pool) print('terms', len(idx['idf'])) with open(os.path.join(BASE, 'pool.pkl'), 'wb') as f: pickle.dump(idx, f) print('saved pool.pkl')