forked from Cockatrice/Magic-Spoiler
-
Notifications
You must be signed in to change notification settings - Fork 1
/
spoilers.py
1349 lines (1275 loc) · 57.1 KB
/
spoilers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import requests
import feedparser
import re
import sys
import os
import shutil
import time
from lxml import html, etree
from PIL import Image
import datetime
import urllib
import json
import xml.dom.minidom
from bs4 import BeautifulSoup as BS
from bs4 import Comment
def scrape_mtgs(url):
return requests.get(url, headers={'Cache-Control':'no-cache', 'Pragma':'no-cache', 'Expires': 'Thu, 01 Jan 1970 00:00:00 GMT'}).text
def parse_mtgs(mtgs, manual_cards=[], card_corrections=[], delete_cards=[], split_cards={}, related_cards=[]):
mtgs = mtgs.replace('utf-16','utf-8')
patterns = ['<b>Name:</b> <b>(?P<name>.*?)<',
'Cost: (?P<cost>\d{0,2}[WUBRGC]*?)<',
'Type: (?P<type>.*?)<',
'Pow/Tgh: (?P<pow>.*?)<',
'Rules Text: (?P<rules>.*?)<br /',
'Rarity: (?P<rarity>.*?)<',
'Set Number: #(?P<setnumber>.*?)/'
]
d = feedparser.parse(mtgs)
cards = []
for entry in d.items()[5][1]:
card = dict(cost='',cmc='',img='',pow='',name='',rules='',type='',
color='', altname='', colorIdentity='', colorArray=[], colorIdentityArray=[], setnumber='', rarity='')
summary = entry['summary']
for pattern in patterns:
match = re.search(pattern, summary, re.MULTILINE|re.DOTALL)
if match:
dg = match.groupdict()
card[dg.items()[0][0]] = dg.items()[0][1]
cards.append(card)
#if we didn't find any cards, let's bail out to prevent overwriting good data
count = 0
for card in cards:
count = count + 1
if count < 1:
sys.exit("No cards found, exiting to prevent file overwrite")
cards2 = []
for card in cards:
if 'rules' in card:
htmltags = re.compile(r'<.*?>')
card['rules'] = htmltags.sub('', card['rules'])
if '//' in card['name'] or 'Aftermath' in card['rules']:
print 'Splitting up Aftermath card ' + card['name']
card1 = card.copy()
card2 = dict(cost='',cmc='',img='',pow='',name='',rules='',type='',
color='', altname='', colorIdentity='', colorArray=[], colorIdentityArray=[], setnumber='', rarity='')
if '//' in card['name']:
card['name'] = card['name'].replace(' // ','//')
card1['name'] = card['name'].split('//')[0]
card2["name"] = card['name'].split('//')[1]
else:
card1['name'] = card['name']
card2["name"] = card['rules'].split('\n\n')[1].strip().split(' {')[0]
card1['rules'] = card['rules'].split('\n\n')[0].strip()
card2["rules"] = "Aftermath" + card['rules'].split('Aftermath')[1]
card2['cost'] = re.findall(r'{.*}',card['rules'])[0].replace('{','').replace('}','').upper()
card2['type'] = re.findall(r'}\n.*\n', card['rules'])[0].replace('}','').replace('\n','')
if 'setnumber' in card:
card1['setnumber'] = card['setnumber'] + 'a'
card2['setnumber'] = card['setnumber'] + 'b'
if 'rarity' in card:
card2['rarity'] = card['rarity']
if not card1['name'] in split_cards:
split_cards[card1['name']] = card2['name']
card1['layout'] = 'aftermath'
card2['layout'] = 'aftermath'
cards2.append(card1)
cards2.append(card2)
else:
cards2.append(card)
cards = cards2
for card in cards:
card['name'] = card['name'].replace(''', '\'')
card['rules'] = card['rules'].replace(''', '\'') \
.replace('<i>', '') \
.replace('</i>', '') \
.replace('"', '"') \
.replace('blkocking', 'blocking')\
.replace('&bull;',u'•')\
.replace('•',u'•')\
.replace('comes into the','enters the')\
.replace('threeor', 'three or')\
.replace('[i]','')\
.replace('[/i]','')\
.replace('Lawlwss','Lawless')\
.replace('Costner',"Counter")
card['type'] = card['type'].replace(' ',' ')\
.replace('Crature', 'Creature')
if card['type'][-1] == ' ':
card['type'] = card['type'][:-1]
if 'cost' in card and len(card['cost']) > 0:
workingCMC = 0
stripCost = card['cost'].replace('{','').replace('}','')
for manaSymbol in stripCost:
if manaSymbol.isdigit():
workingCMC += int(manaSymbol)
elif not manaSymbol == 'X':
workingCMC += 1
card['cmc'] = workingCMC
for c in 'WUBRG': #figure out card's color
if c not in card['colorIdentity']:
if c in card['cost']:
card['color'] += c
card['colorIdentity'] += c
if (c + '}') in card['rules'] or (str.lower(c) + '}') in card['rules']:
if not (c in card['colorIdentity']):
card['colorIdentity'] += c
cleanedcards = []
for card in cards: #let's remove any cards that are named in delete_cards array
if not card['name'] in delete_cards:
cleanedcards.append(card)
cards = cleanedcards
cardarray = []
for card in cards:
dupe = False
for dupecheck in cardarray:
if dupecheck['name'] == card['name']:
dupe = True
if dupe == True:
continue
for cid in card['colorIdentity']:
card['colorIdentityArray'].append(cid)
if 'W' in card['color']:
card['colorArray'].append('White')
if 'U' in card['color']:
card['colorArray'].append('Blue')
if 'B' in card['color']:
card['colorArray'].append('Black')
if 'R' in card['color']:
card['colorArray'].append('Red')
if 'G' in card['color']:
card['colorArray'].append('Green')
cardpower = ''
cardtoughness = ''
if len(card['pow'].split('/')) > 1:
cardpower = card['pow'].split('/')[0]
cardtoughness = card['pow'].split('/')[1]
cardnames = []
cardnumber = card['setnumber'].lstrip('0')
if card['name'] in related_cards:
cardnames.append(card['name'])
cardnames.append(related_cards[card['name']])
cardnumber += 'a'
card['layout'] = 'double-faced'
for namematch in related_cards:
if card['name'] == related_cards[namematch]:
card['layout'] = 'double-faced'
cardnames.append(namematch)
if not card['name'] in cardnames:
cardnames.append(card['name'])
cardnumber += 'b'
cardnames = []
if card['name'] in split_cards:
cardnames.append(card['name'])
cardnames.append(split_cards[card['name']])
cardnumber = cardnumber.replace('b','').replace('a','') + 'a'
if not 'layout' in card:
card['layout'] = 'split'
for namematch in split_cards:
if card['name'] == split_cards[namematch]:
if not 'layout' in card or ('layout' in card and card['layout'] == ''):
card['layout'] = 'split'
cardnames.append(namematch)
if not card['name'] in cardnames:
cardnames.append(card['name'])
cardnumber = cardnumber.replace('b','').replace('a','') + 'b'
if 'number' in card:
if 'b' in card['number'] or 'a' in card['number']:
if not 'layout' in card:
print card['name'] + " has a a/b number but no 'layout'"
card['type'] = card['type'].replace('instant','Instant').replace('sorcery','Sorcery').replace('creature','Creature')
if '-' in card['type']:
subtype = card['type'].split(' - ')[1].strip()
else:
subtype = False
if subtype:
subtypes = subtype.split(' ')
else:
subtypes = False
if card['cmc'] == '':
card['cmc'] = 0
cardjson = {}
#cardjson["id"] = hashlib.sha1(setname + card['name'] + str(card['name']).lower()).hexdigest()
cardjson["cmc"] = card['cmc']
cardjson["manaCost"] = card['cost']
cardjson["name"] = card['name']
cardjson["number"] = cardnumber
#not sure if mtgjson has a list of acceptable rarities, but my application does
#so we'll warn me but continue to write a non-standard rarity (timeshifted?)
#may force 'special' in the future
if card['rarity'] not in ['Mythic Rare','Rare','Uncommon','Common','Special','Basic Land']:
#errors.append({"name": card['name'], "key": "rarity", "value": card['rarity']})
print card['name'] + ' has rarity = ' + card['rarity']
if subtypes:
cardjson['subtypes'] = subtypes
cardjson["rarity"] = card['rarity']
cardjson["text"] = card['rules']
cardjson["type"] = card['type']
workingtypes = card['type']
if ' - ' in workingtypes:
workingtypes = card['type'].split(' - ')[0]
cardjson['types'] = workingtypes.replace('Legendary ','').replace('Snow ','')\
.replace('Elite ','').replace('Basic ','').replace('World ','').replace('Ongoing ','')\
.strip().split(' ')
cardjson["url"] = card['img']
#optional fields
if len(card['colorIdentityArray']) > 0:
cardjson["colorIdentity"] = card['colorIdentityArray']
if len(card['colorArray']) > 0:
cardjson["colors"] = card['colorArray']
if len(cardnames) > 1:
cardjson["names"] = cardnames
if cardpower or cardpower == '0':
cardjson["power"] = cardpower
cardjson["toughness"] = cardtoughness
if card.has_key('loyalty'):
cardjson["loyalty"] = card['loyalty']
if card.has_key('layout'):
cardjson["layout"] = card['layout']
cardarray.append(cardjson)
return [{"cards": cardarray}, split_cards]
def correct_cards(mtgjson, manual_cards=[], card_corrections=[], delete_cards=[]):
mtgjson2 = []
for card in manual_cards:
if 'cmc' not in card:
workingCMC = 0
stripCost = card['manaCost'].replace('{','').replace('}','')
for manaSymbol in stripCost:
if manaSymbol.isdigit():
workingCMC += int(manaSymbol)
elif not manaSymbol == 'X':
workingCMC += 1
if 'types' not in card:
card['types'] = []
workingtypes = card['type']
if ' - ' in workingtypes:
workingtypes = card['type'].split(' - ')[0]
card['types'] = workingtypes.replace('Legendary ', '').replace('Snow ', '') \
.replace('Elite ', '').replace('Basic ', '').replace('World ', '').replace('Ongoing ', '') \
.strip().split(' ')
if 'subtypes' not in card:
# if '—' in card['type']:
# workingSubtypes = card['type'].split('—')[1].strip()
if '-' in card['type']:
workingSubtypes = card['type'].split('-')[1].strip()
if workingSubtypes:
card['subtypes'] = workingSubtypes.split(' ')
colorMap = {
"W": "White",
"U": "Blue",
"B": "Black",
"R": "Red",
"G": "Green"
}
if 'manaCost' in card:
if 'text' in card and not 'Devoid' in card['text']:
for letter in card['manaCost']:
if not letter.isdigit() and not letter == 'X':
if 'colorIdentity' in card:
if not letter in card['colorIdentity']:
card['colorIdentity'] += letter
else:
card['colorIdentity'] = [letter]
if 'colors' in card:
if not colorMap[letter] in card['colors']:
card['colors'].append(colorMap[letter])
else:
card['colors'] = [colorMap[letter]]
if 'text' in card:
for CID in colorMap:
if '{' + CID + '}' in card['text']:
if 'colorIdentity' in card:
if not CID in card['colorIdentity']:
card['colorIdentity'] += CID
else:
card['colorIdentity'] = [CID]
manual_added = []
for card in mtgjson['cards']:
isManual = False
for manualCard in manual_cards:
if card['name'] == manualCard['name']:
mtgjson2.append(manualCard)
manual_added.append(manualCard['name'] + " (overwritten)")
isManual = True
if not isManual and not card['name'] in delete_cards:
mtgjson2.append(card)
for manualCard in manual_cards:
addManual = True
for card in mtgjson['cards']:
if manualCard['name'] == card['name']:
addManual = False
if addManual:
mtgjson2.append(manualCard)
manual_added.append(manualCard['name'])
if manual_added != []:
print "Manual Cards Added: " + str(manual_added).strip('[]')
mtgjson = {"cards": mtgjson2}
return mtgjson
def error_check(mtgjson, card_corrections={}):
errors = []
for card in mtgjson['cards']:
for key in card:
if key == "":
errors.append({"name": card['name'], "key": key, "value": ""})
requiredKeys = ['name','type','types']
for requiredKey in requiredKeys:
if not requiredKey in card:
errors.append({"name": card['name'], "key": key, "missing": True})
if 'text' in card:
card['text'] = card['text'].replace('<i>','').replace('</i>','').replace('<em>','').replace('</em','').replace('(','').replace('•',u'•')
if 'type' in card:
if 'Planeswalker' in card['type']:
if not 'loyalty' in card:
errors.append({"name": card['name'], "key": "loyalty", "value": ""})
if not card['rarity'] == 'Mythic Rare':
errors.append({"name": card['name'], "key": "rarity", "value": card['rarity']})
if not 'subtypes' in card:
errors.append({"name": card['name'], "key": "subtypes", "oldvalue": "", "newvalue": card['name'].split(" ")[0], "fixed": True})
if not card['name'].split(' ')[0] == 'Ob' and not card['name'].split(' ') == 'Nicol':
card["subtypes"] = card['name'].split(" ")[0]
else:
card["subtypes"] = card['name'].split(" ")[1]
if not 'types' in card:
#errors.append({"name": card['name'], "key": "types", "fixed": True, "oldvalue": "", "newvalue": ["Planeswalker"]})
card['types'] = ["Planeswalker"]
elif not "Planeswalker" in card['types']:
#errors.append({"name": card['name'], "key": "types", "fixed": True, "oldvalue": card['types'], "newvalue": card['types'] + ["Planeswalker"]})
card['types'].append("Planeswalker")
if 'Creature' in card['type']:
if not 'power' in card:
errors.append({"name": card['name'], "key": "power", "value": ""})
if not 'toughness' in card:
errors.append({"name": card['name'], "key": "toughness", "value": ""})
if not 'subtypes' in card:
errors.append({"name": card['name'], "key": "subtypes", "value": ""})
if 'manaCost' in card:
workingCMC = 0
stripCost = card['manaCost'].replace('{','').replace('}','')
for manaSymbol in stripCost:
if manaSymbol.isdigit():
workingCMC += int(manaSymbol)
elif not manaSymbol == 'X':
workingCMC += 1
if not 'cmc' in card:
errors.append({"name": card['name'], "key": "cmc", "value": ""})
elif not card['cmc'] == workingCMC:
errors.append({"name": card['name'], "key": "cmc", "oldvalue": card['cmc'], "newvalue": workingCMC, "fixed": True, "match": card['manaCost']})
card['cmc'] = workingCMC
if not 'cmc' in card:
errors.append({"name": card['name'], "key": "cmc", "value": ""})
else:
if not isinstance(card['cmc'], int):
errors.append({"name": card['name'], "key": "cmc", "oldvalue": card['cmc'], "newvalue": int(card['cmc']), "fixed": True})
card['cmc'] = int(card['cmc'])
else:
if card['cmc'] > 0:
if not 'manaCost' in card:
errors.append({"name": card['name'], "key": "manaCost", "value": "", "match": card['cmc']})
else:
if 'manaCost' in card:
errors.append({"name": card['name'], "key": "manaCost", "oldvalue": card['manaCost'], "fixed": True})
del card["manaCost"]
if 'colors' in card:
if not 'colorIdentity' in card:
if 'text' in card:
if not 'devoid' in card['text'].lower():
errors.append({"name": card['name'], "key": "colorIdentity", "value": ""})
else:
errors.append({"name": card['name'], "key": "colorIdentity", "value": ""})
if 'colorIdentity' in card:
if not 'colors' in card:
#this one will false positive on emerge cards
if not 'Land' in card['type'] and not 'Artifact' in card['type'] and not 'Eldrazi' in card['type']:
if 'text' in card:
if not 'emerge' in card['text'].lower() and not 'devoid' in card['text'].lower():
errors.append({"name": card['name'], "key": "colors", "value": ""})
else:
errors.append({"name": card['name'], "key": "colors", "value": ""})
#if not 'Land' in card['type'] and not 'Artifact' in card['type'] and not 'Eldrazi' in card['type']:
# errors.append({"name": card['name'], "key": "colors", "value": ""})
if not 'url' in card:
errors.append({"name": card['name'], "key": "url", "value": ""})
elif len(card['url']) < 10:
errors.append({"name": card['name'], "key": "url", "value": ""})
if not 'number' in card:
errors.append({"name": card['name'], "key": "number", "value": ""})
if not 'types' in card:
errors.append({"name": card['name'], "key": "types", "value": ""})
for card in mtgjson['cards']: #we're going to loop through again and make sure split cards get paired
if 'layout' in card:
if card['layout'] == 'split' or card['layout'] == 'meld' or card['layout'] == 'aftermath':
if not 'names' in card:
errors.append({"name": card['name'], "key": "names", "value": ""})
else:
for related_card_name in card['names']:
if related_card_name != card['name']:
related_card = False
for card2 in mtgjson['cards']:
if card2['name'] == related_card_name:
related_card = card2
if not related_card:
errors.append({"name": card['name'], "key": "names", "value": card['names']})
else:
if 'colors' in related_card:
for color in related_card['colors']:
if not color in card['colors']:
card['colors'].append(color)
if 'colorIdentity' in related_card:
for colorIdentity in related_card['colorIdentity']:
if not colorIdentity in card['colorIdentity']:
card['colorIdentity'].append(colorIdentity)
if 'number' in card:
if not 'a' in card['number'] and not 'b' in card['number'] and not 'c' in card['number']:
errors.append({"name": card['name'], "key": "number", "value": card['number']})
for card in mtgjson['cards']:
for cardCorrection in card_corrections:
if card['name'] == cardCorrection:
for correctionType in card_corrections[cardCorrection]:
# if not correctionType in card and correctionType not in :
# sys.exit("Invalid correction for " + cardCorrection + " of type " + card)
if not correctionType == 'name':
if correctionType == 'img':
card['url'] = card_corrections[cardCorrection][correctionType]
else:
card[correctionType] = card_corrections[cardCorrection][correctionType]
if 'name' in card_corrections[cardCorrection]:
card['name'] = card_corrections[cardCorrection]['name']
return [mtgjson, errors]
def remove_corrected_errors(errorlog=[], card_corrections=[], print_fixed=False):
errorlog2 = {}
for error in errorlog:
if not print_fixed:
if 'fixed' in error and error['fixed'] == True:
continue
removeError = False
for correction in card_corrections:
for correction_type in card_corrections[correction]:
if error['name'] == correction:
if error['key'] == correction_type:
removeError = True
if not removeError:
if not error['name'] in errorlog2:
errorlog2[error['name']] = {}
if not 'value' in error:
error['value'] = ""
errorlog2[error['name']][error['key']] = error['value']
return errorlog2
def get_scryfall(setUrl):
#getUrl = 'https://api.scryfall.com/cards/search?q=++e:'
#setUrl = getUrl + setname.lower()
setDone = False
scryfall = []
while setDone == False:
setcards = requests.get(setUrl)
setcards = setcards.json()
if setcards.has_key('data'):
scryfall.append(setcards['data'])
else:
setDone = True
#print setUrl
#print setcards
print 'No Scryfall data'
scryfall = ['']
time.sleep(.1)
if setcards.has_key('has_more'):
if setcards['has_more'] == True:
setUrl = setcards['next_page']
else:
setDone = True
else:
setDone = True
if not scryfall[0] == '':
scryfall = convert_scryfall(scryfall[0])
return {'cards': scryfall}
else:
return {'cards': []}
def convert_scryfall(scryfall):
cards2 = []
for card in scryfall:
card2 = {}
card2['cmc'] = int((card['cmc']).split('.')[0])
if card.has_key('mana_cost'):
card2['manaCost'] = card['mana_cost'].replace('{','').replace('}','')
else:
card2['manaCost'] = ''
card2['name'] = card['name']
card2['number'] = card['collector_number']
card2['rarity'] = card['rarity'].replace('mythic','mythic rare').title()
if card.has_key('oracle_text'):
card2['text'] = card['oracle_text'].replace(u"\u2014",'-').replace(u"\u2212","-")
else:
card2['text'] = ''
card2['url'] = card['image_uri']
if not 'type_line' in card:
card['type_line'] = 'Unknown'
card2['type'] = card['type_line'].replace(u'—','-')
cardtypes = card['type_line'].split(u' — ')[0].replace('Legendary ','').replace('Snow ','')\
.replace('Elite ','').replace('Basic ','').replace('World ','').replace('Ongoing ','')
cardtypes = cardtypes.split(' ')
if u' — ' in card['type_line']:
cardsubtypes = card['type_line'].split(u' — ')[1]
if ' ' in cardsubtypes:
card2['subtypes'] = cardsubtypes.split(' ')
else:
card2['subtypes'] = [cardsubtypes]
if 'Legendary' in card['type_line']:
if card2.has_key('supertypes'):
card2['supertypes'].append('Legendary')
else:
card2['supertypes'] = ['Legendary']
if 'Snow' in card['type_line']:
if card2.has_key('supertypes'):
card2['supertypes'].append('Snow')
else:
card2['supertypes'] = ['Snow']
if 'Elite' in card['type_line']:
if card2.has_key('supertypes'):
card2['supertypes'].append('Elite')
else:
card2['supertypes'] = ['Elite']
if 'Basic' in card['type_line']:
if card2.has_key('supertypes'):
card2['supertypes'].append('Basic')
else:
card2['supertypes'] = ['Basic']
if 'World' in card['type_line']:
if card2.has_key('supertypes'):
card2['supertypes'].append('World')
else:
card2['supertypes'] = ['World']
if 'Ongoing' in card['type_line']:
if card2.has_key('supertypes'):
card2['supertypes'].append('Ongoing')
else:
card2['supertypes'] = ['Ongoing']
card2['types'] = cardtypes
if card.has_key('color_identity'):
card2['colorIdentity'] = card['color_identity']
if card.has_key('colors'):
if not card['colors'] == []:
card2['colors'] = []
if 'W' in card['colors']:
card2['colors'].append("White")
if 'U' in card['colors']:
card2['colors'].append("Blue")
if 'B' in card['colors']:
card2['colors'].append("Black")
if 'R' in card['colors']:
card2['colors'].append("Red")
if 'G' in card['colors']:
card2['colors'].append("Green")
#card2['colors'] = card['colors']
if card.has_key('all_parts'):
card2['names'] = []
for partname in card['all_parts']:
card2['names'].append(partname['name'])
if card.has_key('power'):
card2['power'] = card['power']
if card.has_key('toughness'):
card2['toughness'] = card['toughness']
if card.has_key('layout'):
if card['layout'] != 'normal':
card2['layout'] = card['layout']
if card.has_key('loyalty'):
card2['loyalty'] = card['loyalty']
if card.has_key('artist'):
card2['artist'] = card['artist']
#if card.has_key('source'):
# card2['source'] = card['source']
#if card.has_key('rulings'):
# card2['rulings'] = card['rulings']
if card.has_key('flavor_text'):
card2['flavor'] = card['flavor_text']
if card.has_key('multiverse_id'):
card2['multiverseid'] = card['multiverse_id']
cards2.append(card2)
return cards2
print
def smash_mtgs_scryfall(mtgs, scryfall):
for mtgscard in mtgs['cards']:
cardFound = False
for scryfallcard in scryfall['cards']:
if scryfallcard['name'] == mtgscard['name']:
for key in scryfallcard:
if key in mtgscard:
if not mtgscard[key] == scryfallcard[key]:
try:
print "%s's key %s\nMTGS : %s\nScryfall: %s" % (mtgscard['name'], key, mtgscard[key], scryfallcard[key])
except:
print "Error printing Scryfall vs MTGS debug info for " + mtgscard['name']
pass
cardFound = True
if not cardFound:
print "MTGS has card %s and Scryfall does not." % mtgscard['name']
for scryfallcard in scryfall['cards']:
cardFound = False
for mtgscard in mtgs['cards']:
if scryfallcard['name'] == mtgscard['name']:
cardFound = True
if not cardFound:
print "Scryfall has card %s and MTGS does not." % scryfallcard['name']
return mtgs
def scrape_fullspoil(url="http://magic.wizards.com/en/articles/archive/card-image-gallery/hour-devastation", setinfo={"setname":"HOU"}, showRarityColors=False, showFrameColors=False, manual_cards=[], delete_cards=[], split_cards=[]):
if 'setlongname' in setinfo:
url = 'http://magic.wizards.com/en/articles/archive/card-image-gallery/' + setinfo['setlongname'].lower().replace('of', '').replace(
' ', ' ').replace(' ', '-')
page = requests.get(url)
tree = html.fromstring(page.content)
cards = []
cardtree = tree.xpath('//*[@id="content-detail-page-of-an-article"]')
for child in cardtree:
cardElements = child.xpath('//*/p/img')
cardcount = 0
for cardElement in cardElements:
card = {
"name": cardElement.attrib['alt'].replace(u"\u2019",'\'').split(' /// ')[0],
"img": cardElement.attrib['src']
}
card["url"] = card["img"]
#card["cmc"] = 0
#card["manaCost"] = ""
#card["type"] = ""
#card["types"] = []
#card["text"] = ""
#card["colorIdentity"] = [""]
#if card['name'] in split_cards:
# card["names"] = [card['name'], split_cards[card['name']]]
# card["layout"] = "split"
#notSplit = True
#for backsplit in split_cards:
# if card['name'] == split_cards[backsplit]:
# notSplit = False
#if not card['name'] in delete_cards:
cards.append(card)
cardcount += 1
fullspoil = { "cards": cards }
print "Spoil Gallery has " + str(cardcount) + " cards."
download_images(fullspoil['cards'], setinfo['setname'])
fullspoil = get_rarities_by_symbol(fullspoil, setinfo['setname'])
fullspoil = get_colors_by_frame(fullspoil, setinfo['setname'])
return fullspoil
def download_images(mtgjson, setcode):
if not os.path.isdir('images/' + setcode):
os.makedirs('images/' + setcode)
if 'cards' in mtgjson:
jsoncards = mtgjson['cards']
else:
jsoncards = mtgjson
for card in jsoncards:
if card['url']:
if os.path.isfile('images/' + setcode + '/' + card['name'].replace(' // ','') + '.jpg'):
continue
#print 'Downloading ' + card['url'] + ' to images/' + setcode + '/' + card['name'].replace(' // ','') + '.jpg'
urllib.urlretrieve(card['url'], 'images/' + setcode + '/' + card['name'].replace(' // ','') + '.jpg')
def get_rarities_by_symbol(fullspoil, setcode, split_cards=[]):
symbolPixels = (240, 219, 242, 221)
highVariance = 15
colorAverages = {
"Common": [30, 27, 28],
"Uncommon": [121, 155, 169],
"Rare": [166, 143, 80],
"Mythic Rare": [201, 85, 14]
}
symbolCount = 0
for card in fullspoil['cards']:
try:
cardImage = Image.open('images/' + setcode + '/' + card['name'].replace(' // ','') + '.jpg')
except:
continue
pass
if '//' in card['name']:
setSymbol = cardImage.crop((240, 138, 242, 140))
else:
setSymbol = cardImage.crop(symbolPixels)
cardHistogram = setSymbol.histogram()
reds = cardHistogram[0:256]
greens = cardHistogram[256:256 * 2]
blues = cardHistogram[256 * 2: 256 * 3]
reds = sum(i * w for i, w in enumerate(reds)) / sum(reds)
greens = sum(i * w for i, w in enumerate(greens)) / sum(greens)
blues = sum(i * w for i, w in enumerate(blues)) / sum(blues)
variance = 768
for color in colorAverages:
colorVariance = 0
colorVariance = colorVariance + abs(colorAverages[color][0] - reds)
colorVariance = colorVariance + abs(colorAverages[color][1] - greens)
colorVariance = colorVariance + abs(colorAverages[color][2] - blues)
if colorVariance < variance:
variance = colorVariance
card['rarity'] = color
if variance > highVariance:
# if a card isn't close to any of the colors, it's probably a planeswalker? make it mythic.
print card['name'], 'has high variance of', variance, ', closest rarity is', card['rarity']
card['rarity'] = "Mythic Rare"
print card['name'], '$', reds, greens, blues
if symbolCount < 10:
setSymbol.save('images/' + card['name'].replace(' // ','') + '.symbol.jpg')
symbolCount += 1
return fullspoil
def get_colors_by_frame(fullspoil, setcode, split_cards={}):
framePixels = (20, 11, 76, 16)
highVariance = 10
colorAverages = {
"White": [231,225,200],
"Blue": [103,193,230],
"Black": [58, 61, 54],
"Red": [221, 122, 101],
"Green": [118, 165, 131],
"Multicolor": [219, 200, 138],
"Artifact": [141, 165, 173],
"Colorless": [216, 197, 176],
}
symbolCount = 0
for card in fullspoil['cards']:
try:
cardImage = Image.open('images/' + setcode + '/' + card['name'].replace(' // ','') + '.jpg')
except:
continue
pass
cardColor = cardImage.crop(framePixels)
cardHistogram = cardColor.histogram()
reds = cardHistogram[0:256]
greens = cardHistogram[256:256 * 2]
blues = cardHistogram[256 * 2: 256 * 3]
reds = sum(i * w for i, w in enumerate(reds)) / sum(reds)
greens = sum(i * w for i, w in enumerate(greens)) / sum(greens)
blues = sum(i * w for i, w in enumerate(blues)) / sum(blues)
variance = 768
for color in colorAverages:
colorVariance = 0
colorVariance = colorVariance + abs(colorAverages[color][0] - reds)
colorVariance = colorVariance + abs(colorAverages[color][1] - greens)
colorVariance = colorVariance + abs(colorAverages[color][2] - blues)
if colorVariance < variance:
variance = colorVariance
card['colors'] = [color]
return fullspoil
def get_image_urls(mtgjson, isfullspoil, setname, setlongname, setSize=269, setinfo=False):
IMAGES = 'http://magic.wizards.com/en/content/' + setlongname.lower().replace(' ', '-') + '-cards'
IMAGES2 = 'http://mythicspoiler.com/newspoilers.html'
IMAGES3 = 'http://magic.wizards.com/en/articles/archive/card-image-gallery/' + setlongname.lower().replace('of','').replace(' ',' ').replace(' ', '-')
text = requests.get(IMAGES).text
text2 = requests.get(IMAGES2).text
text3 = requests.get(IMAGES3).text
wotcpattern = r'<img alt="{}.*?" src="(?P<img>.*?\.png)"'
wotcpattern2 = r'<img src="(?P<img>.*?\.png).*?alt="{}.*?"'
mythicspoilerpattern = r' src="' + setname.lower() + '/cards/{}.*?.jpg">'
WOTC = []
for c in mtgjson['cards']:
match = re.search(wotcpattern.format(c['name'].replace('\'','’')), text, re.DOTALL)
if match:
c['url'] = match.groupdict()['img']
else:
match3 = re.search(wotcpattern2.format(c['name'].replace('\'','’')), text3)
if match3:
c['url'] = match3.groupdict()['img']
else:
match4 = re.search(wotcpattern.format(c['name'].replace('\'','’')), text3, re.DOTALL)
if match4:
c['url'] = match4.groupdict()['img']
else:
if 'names' in c:
mythicname = c['names'][0] + c['names'][1]
else:
mythicname = c['name']
match2 = re.search(mythicspoilerpattern.format(mythicname.lower().replace(' ', '').replace(''', '').replace('-', '').replace('\'','').replace(',', '')), text2, re.DOTALL)
if match2 and not isfullspoil:
c['url'] = match2.group(0).replace(' src="', 'http://mythicspoiler.com/').replace('">', '')
pass
#if ('Creature' in c['type'] and not c.has_key('power')) or ('Vehicle' in c['type'] and not c.has_key('power')):
# print(c['name'] + ' is a creature w/o p/t img: ' + c['url'])
if 'wizards.com' in c['url']:
WOTC.append(c['name'])
if setinfo:
if 'mtgsurl' in setinfo and 'mtgscardpath' in setinfo:
mtgsImages = scrape_mtgs_images(setinfo['mtgsurl'], setinfo['mtgscardpath'], WOTC)
for card in mtgjson['cards']:
if card['name'] in mtgsImages:
if mtgsImages[card['name']]['url'] != '':
card['url'] = mtgsImages[card['name']]['url']
for card in mtgjson['cards']:
if len(str(card['url'])) < 10:
print(card['name'] + ' has no image.')
return mtgjson
def smash_fullspoil(mtgjson, fullspoil):
different_keys = {}
for mtgjson_card in mtgjson['cards']:
for fullspoil_card in fullspoil['cards']:
if mtgjson_card['name'] == fullspoil_card['name']:
for key in fullspoil_card:
if key in mtgjson_card:
if mtgjson_card[key] != fullspoil_card[key] and key != 'colors':
if not fullspoil_card['name'] in different_keys:
different_keys[fullspoil_card['name']] = {key: fullspoil_card[key]}
else:
different_keys[fullspoil_card['name']][key] = fullspoil_card[key]
for fullspoil_card in fullspoil['cards']:
WOTC_only = []
match = False
for mtgjson_card in mtgjson['cards']:
if mtgjson_card['name'] == fullspoil_card['name']:
match = True
if not match:
WOTC_only.append(fullspoil_card['name'])
if len(WOTC_only) > 0:
print "WOTC only cards: "
print WOTC_only
print different_keys
def scrape_mtgs_images(url='http://www.mtgsalvation.com/spoilers/183-hour-of-devastation', mtgscardurl='http://www.mtgsalvation.com/cards/hour-of-devastation/', exemptlist=[]):
page = requests.get(url)
tree = html.fromstring(page.content)
cards = {}
cardstree = tree.xpath('//*[contains(@class, "log-card")]')
for child in cardstree:
if child.text in exemptlist:
continue
childurl = mtgscardurl + child.attrib['data-card-id'] + '-' + child.text.replace(' ','-').replace("'","").replace(',','').replace('-//','')
cardpage = requests.get(childurl)
tree = html.fromstring(cardpage.content)
cardtree = tree.xpath('//img[contains(@class, "card-spoiler-image")]')
try:
cardurl = cardtree[0].attrib['src']
except:
cardurl = ''
pass
cards[child.text] = {
"url": cardurl
}
time.sleep(.2)
return cards
def write_xml(mtgjson, setname, setlongname, setreleasedate, split_cards=[]):
if not os.path.isdir('out/'):
os.makedirs('out/')
cardsxml = open('out/' + setname + '.xml', 'w+')
cardsxml.truncate()
count = 0
dfccount = 0
newest = ''
related = 0
cardsxml.write("<?xml version='1.0' encoding='UTF-8'?>\n"
"<cockatrice_carddatabase version='3'>\n"
"<sets>\n<set>\n<name>"
+ setname +
"</name>\n"
"<longname>"
+ setlongname +
"</longname>\n"
"<settype>Expansion</settype>\n"
"<releasedate>"
+ setreleasedate +
"</releasedate>\n"
"</set>\n"
"</sets>\n"
"<cards>\n")
#print mtgjson
for card in mtgjson["cards"]:
for carda in split_cards:
if card["name"] == split_cards[carda]:
continue
if count == 0:
newest = card["name"]
count += 1
name = card["name"]
if card.has_key("manaCost"):
manacost = card["manaCost"].replace('{', '').replace('}', '')
else:
manacost = ""
if card.has_key("power") or card.has_key("toughness"):
if card["power"]:
pt = str(card["power"]) + "/" + str(card["toughness"])
else:
pt = 0
else:
pt = 0
if card.has_key("text"):
text = card["text"]
else:
text = ""
cardcmc = str(card['cmc'])
cardtype = card["type"]
if card.has_key("names"):
if "layout" in card:
if card['layout'] == 'split' or card['layout'] == 'aftermath':
if 'names' in card:
if card['name'] == card['names'][0]:
for jsoncard in mtgjson["cards"]:
if jsoncard['name'] == card['names'][1]:
cardtype += " // " + jsoncard["type"]
manacost += " // " + (jsoncard["manaCost"]).replace('{', '').replace('}', '')
cardcmc += " // " + str(jsoncard["cmc"])
text += "\n---\n" + jsoncard["text"]
name += " // " + jsoncard['name']
else:
print card["name"] + " has names, but layout != split"
else:
print card["name"] + " has multiple names and no 'layout' key"
tablerow = "1"
if "Land" in cardtype:
tablerow = "0"
elif "Sorcery" in cardtype:
tablerow = "3"
elif "Instant" in cardtype:
tablerow = "3"
elif "Creature" in cardtype:
tablerow = "2"
if 'number' in card:
if 'b' in card['number']:
if 'layout' in card:
if card['layout'] == 'split' or card['layout'] == 'aftermath':
#print "We're skipping " + card['name'] + " because it's the right side of a split card"
continue
cardsxml.write("<card>\n")
cardsxml.write("<name>" + name.encode('utf-8') + "</name>\n")
cardsxml.write('<set rarity="' + card['rarity'] + '" picURL="' + card["url"] + '">' + setname + '</set>\n')
cardsxml.write("<manacost>" + manacost.encode('utf-8') + "</manacost>\n")
cardsxml.write("<cmc>" + cardcmc + "</cmc>\n")
if card.has_key('colors'):
colorTranslate = {
"White": "W",
"Blue": "U",
"Black": "B",
"Red": "R",
"Green": "G"
}
for color in card['colors']:
cardsxml.write('<color>' + colorTranslate[color] + '</color>\n')
if name + ' enters the battlefield tapped' in text:
cardsxml.write("<cipt>1</cipt>\n")
cardsxml.write("<type>" + cardtype.encode('utf-8') + "</type>\n")
if pt:
cardsxml.write("<pt>" + pt + "</pt>\n")
if card.has_key('loyalty'):
cardsxml.write("<loyalty>" + str(card['loyalty']) + "</loyalty>\n")
cardsxml.write("<tablerow>" + tablerow + "</tablerow>\n")
cardsxml.write("<text>" + text.encode('utf-8') + "</text>\n")
if related:
# for relatedname in related:
cardsxml.write("<related>" + related.encode('utf-8') + "</related>\n")
related = ''
cardsxml.write("</card>\n")
cardsxml.write("</cards>\n</cockatrice_carddatabase>")