File size: 15,713 Bytes
fef304e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a29888
fef304e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a29888
 
fef304e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#a program to build a training data set for Stable Diffusion for Magic: The Gathering
#it will pull all data from a saved JSON file, parse it, and save an image file and corresponding text file for each card

import requests
import json
import os
import random
import time


#set up the directory to save the images and data to
directory = './mtg-training-data/'  #this is the directory where the images and data will be saved
if not os.path.exists(directory):
    os.makedirs(directory)  #make the directory if it doesn't exist already
        
#our json file location
json_filename = './mtg-training-data/mtgdata.json'

#save a normal, single-faced card
def save_card_main(card):
    #get the image url and filename
    img_url = card['image_uris'].get('art_crop')
    filename = which_filename(card)
    #clean up any characters that might make the filename invalid
    filename = filename.replace('/', '-')
    filename = filename.replace(':', '-')
    filename = filename.replace('?', '')
    filename = filename.replace('!', '')
    filename = filename.replace('\'', '-')
    filename = filename.replace('\"', '')
    filename = filename.replace(' ', '_')
    filename = filename.replace('(', '')
    filename = filename.replace(')', '')
    filename = filename.replace(',', '')
    filename = filename.replace('’', '')
    filename = filename.replace('–', '-')
    filename = filename.replace('—', '-')
    filename = filename.replace('…', '')
    #save the image unless it already exists
    if not os.path.isfile('{}{}'.format(directory, filename)):
        #add a 0.1 second delay if we get blocked by the server
        #time.sleep(0.1)
        save_image(img_url, filename)
    #get the data
    data = return_data(card)
    #save the data
    save_data(data, filename)
    

#determine the filename we're saving the image to; format is cardname_setcode_illustration_id.jpg
def which_filename(card):
    if card.get('flavor_name'):
        name = card['flavor_name']
    #if there's no illustration_id, use multiverse_ids as a backup
    if card.get('illustration_id'):
        id = card['illustration_id']
    else:
        id = card['multiverse_ids'][0]
    id = str(id)
    filename = card['name'] + '_' + card['set'] + '_' + id + '.jpg'
    return filename

#save the image
def save_image(img_url, filename):
    response = requests.get(img_url)
    with open('{}{}'.format(directory, filename), 'wb') as f:
        f.write(response.content)
    #report to stdout that we just saved the url to the filename
    print('Saved {} to {}'.format(img_url, filename))


#save the data as a text file with the same name as the image
def save_data(data, filename):
    filename = filename.replace('.jpg', '.txt')
    with open('{}{}'.format(directory, filename), 'w', encoding="utf8") as f:
        f.write(str(data))
    #report to stdout what we just saved and to what filename
    print('Saved {} to {}'.format(data, filename))
    
#get the data we want from the card and return it
#from the json, we're getting card name, artist, the year of release, color, type, rarity, set name, set code, mana cost, any watermarks, power/toughness, any keywords, universes beyond info
def return_data(card):    
    glue = 'MTG card art'
    name = card['name']
    #look for a flavor name, change name to flavor name if it exists
    if card.get('flavor_name'):
        name = card['flavor_name']
    #replace ' with ’ in name for placeholder purposes
    name = name.replace('\'', '’')
    artist = 'by ' + card['artist']
    #replace ' with ’ in artist for placeholder purposes
    artist = artist.replace('\'', '’')
    year = get_year(card['released_at'])
    if card.get('colors'):
        colors_english = mtg_color_to_english(card['colors'])
        colors = clean_colors(card['colors'])
    else:
        colors_english = 'Colorless'
        colors = 'C'
    card_type = card['type_line']
    rarity = card['rarity']
    set_name = card['set_name']
    set_code = ' '
    set_code = card['set']
    set_type = card['set_type']
    plane = ' '
    plane = determine_plane(set_code)
    if card.get('watermark'):
        watermark = card['watermark']
    else: watermark = 'WATERMARK_PLACEHOLDER'
    mana_cost = clean_data(card['mana_cost'])
    if card.get('security_stamp'):
        security_stamp = parse_security_stamp(card['security_stamp'])
    else: security_stamp = 'SECURITY_STAMP_PLACEHOLDER'
    if card.get('power'):
        power = card['power']
    else: power = 'POWER_PLACEHOLDER'
    if card.get('toughness'):
        toughness = card['toughness']
    else: toughness = 'TOUGHNESS_PLACEHOLDER'
    power_toughness = power + '/' + toughness
    if card.get('keywords'):
        keywords = card['keywords']
    else: keywords = 'KEYWORDS_PLACEHOLDER'
    if card.get('promo_types'):
        promo_types = card['promo_types']
    else: promo_types = 'PROMO_TYPES_PLACEHOLDER'
    if card.get('story_spotlight'):
        story_spotlight = card['story_spotlight']
    else: story_spotlight = 'SPOTLIGHT_PLACEHOLDER'
    #at one point I put extra spaces in as a quick fix to make the txt files come out right - I have no idea if they are still needed
    extra_space = ' '
    #put it all together
    data = glue, name, artist, year, colors_english, colors, card_type, rarity, set_name, set_code, plane, set_type, watermark, extra_space, mana_cost, extra_space, security_stamp, power_toughness, keywords, promo_types, story_spotlight
    #then clean it up
    data = clean_data(data)
    return data
   
#determine the plane from the set code
def determine_plane(set_code):
    #convert set_code to uppercase
    set_code = set_code.upper()
    if set_code == 'ALA' or set_code == 'CON' or set_code == 'ARB':
        plane = 'Alara'
    elif set_code == 'AKH' or set_code == 'HOU':
        plane = 'Amonkhet'
    elif set_code == 'STX':
        plane = 'Arcavios'
    elif set_code == 'SNC':
        plane = 'Capenna'
    elif set_code == 'ELD':
        plane = 'Eldraine'
    elif set_code == 'CNS' or set_code == 'CN2':
        plane = 'Fiora'
    elif set_code == 'IKO':
        plane = 'Ikoria'
    elif set_code == 'ISD' or set_code == 'DKA' or set_code == 'AVR' or set_code == 'SOI' or set_code == 'EMN' or set_code == 'MID' or set_code == 'VOW':
        plane = 'Innistrad'
    elif set_code == 'IXL' or set_code == 'RIX':
        plane = 'Ixalan'
    elif set_code == 'KLD' or set_code == 'AER':
        plane = 'Kaladesh'
    elif set_code == 'KHM':
        plane = 'Kaldheim'
    elif set_code == 'SOK' or set_code == 'BOK' or set_code == 'CHK':
        plane = 'Kamigawa, past'
    elif set_code == 'NEC':
        plane = 'Kamigawa, present'
    elif set_code == 'BBD':
        plane = 'Kylem'
    elif set_code == 'LOR' or set_code == 'MOR':
        plane = 'Lorwyn, LorShad'
    elif set_code == 'SHM' or set_code == 'EVE':
        plane = 'Shadowmoor, LorShad'
    elif set_code == 'MMQ':
        plane = 'Mercadia'
    elif set_code == 'NPH':
        plane = 'New Phyrexia'
    elif set_code == 'MRD' or set_code == 'DST' or set_code == '5DN' or set_code == 'SOM' or set_code == 'MBS':
        plane = 'Mirrodin'
    elif set_code == 'ARN':
        plane = 'Rabiah'
    elif set_code == 'TMP' or set_code == 'STH' or set_code == 'EXO' or set_code == 'NEM':
        plane = 'Rath'
    elif set_code == 'RAV' or set_code == 'GPT' or set_code == 'DIS' or set_code == 'RTR' or set_code == 'GTC' or set_code == 'DGM' or set_code == 'GRN' or set_code == 'RNA' or set_code == 'WAR':
        plane = 'Ravnica'
    elif set_code == 'M10' or set_code == 'M11' or set_code == 'M12' or set_code == 'M13' or set_code == 'M14' or set_code == 'M15':
        plane = 'Shandalar'
    elif set_code == "KTK" or set_code == "FRF" or set_code == "DTK":
        plane = 'Tarkir'
    elif set_code == 'THS' or set_code == 'BNG' or set_code == 'JOU' or set_code == 'THB':
        plane = 'Theros'
    elif set_code == 'HML':
        plane = 'Ulgrotha'
    elif set_code == 'ZEN' or set_code == 'WWK' or set_code == 'ROE' or set_code == 'BFZ' or set_code == 'OGW' or set_code == 'ZNR':
        plane = 'Zendikar'

#Dominaria
    elif set_code == 'LEA' or set_code == 'LEG' or set_code == 'DOM' or set_code == 'DMU':
        plane = 'Dominaria'
    elif set_code == 'ATQ' or set_code == 'DRK':
        plane = 'Dominaria, Terisiare'
    elif set_code == 'ICE' or set_code == 'ALL' or set_code == 'CSP':
        plane = 'Dominaria, Terisiare, Ice Age'
    elif set_code == 'BRO':
        plane = 'Dominaria, past'
    elif set_code == 'MIR' or set_code == 'VIS' or set_code == 'WTH' or set_code == 'PCY':
        plane = 'Dominaria, Jamuraa'
    elif set_code == 'TSP' or set_code == 'PLC' or set_code == 'FUT':
        plane = 'Dominaria, Time Spiral'
    elif set_code == 'INV' or set_code == 'PLS' or set_code == 'APC':
        plane = 'Dominaria, Phyrexian Invasion'
    elif set_code == 'ODY' or set_code == 'TOR' or set_code == 'JUD' or set_code == 'ONS' or set_code == 'LGN' or set_code == 'SCG':
        plane = 'Dominaria, Otaria'
    else:
        plane = ' '
    return plane

#clean the colors up, remove the square brackets, quotes, commas and spaces
def clean_colors(colors):
    colors = str(colors)
    colors = colors.replace('[', '')
    colors = colors.replace(']', '')
    colors = colors.replace('\'', '')
    colors = colors.replace(',', '')
    colors = colors.replace(' ', '')
    #then add a space back at the start
    #now rearrange the colors so they're in WUBRG order until there are no more rearrangements to be made
    while True:
        colors = colors.replace('UW', 'WU')
        colors = colors.replace('BW', 'WB')
        colors = colors.replace('RW', 'WR')
        colors = colors.replace('GW', 'WG')
        colors = colors.replace('BU', 'UB')
        colors = colors.replace('GU', 'UG')
        colors = colors.replace('RU', 'UR')
        colors = colors.replace('RB', 'BR')
        colors = colors.replace('GB', 'BG')
        colors = colors.replace('GR', 'RG')
        if 'UW' not in colors and 'BW' not in colors and 'RW' not in colors and 'GW' not in colors and 'BU' not in colors and 'GU' not in colors and 'RU' not in colors and 'RB' not in colors and 'GB' not in colors and 'GR' not in colors:
            break
    return colors
#figure out what the security stamp is telling us
def parse_security_stamp(security_stamp):
    if security_stamp:
        if security_stamp == 'acorn':
            return 'acorn'
        if security_stamp == 'triangle':
            return 'Universes Beyond'
        if security_stamp == 'arena':
            return 'Arena'
        if security_stamp == 'circle':
            ##return 'Signature Spellbook'
            #return nothing for now
            return None
        if security_stamp == 'heart':
            return 'My Little Pony'
        if security_stamp == 'oval':
            return None
    else: return None


#remove all characters other than WUBRG, then convert letter by letter
def mtg_color_to_english(colors):
    #remove all characters other than WUBRG
    colors = ''.join([c for c in colors if c in 'WUBRG'])
    #for each letter in colors, add the corresponding color to colors_english, plus a comma and space
    colors_english = ''
    for c in colors:
        if c == 'W':
            colors_english += 'White, '
        if c == 'U':
            colors_english += 'Blue, '
        if c == 'B':
            colors_english += 'Black, '
        if c == 'R':
            colors_english += 'Red, '
        if c == 'G':
            colors_english += 'Green, '
        if c == '':
            colors_english += 'Colorless, '
    #remove the last comma and space
    colors_english = colors_english[:-2]
    return colors_english
        
#get the year from the release date
def get_year(date):
    year = date[:4]
    return year

#special function for double-faced cards - we are going to save the front and back separately
#scryfall treats them as a single card, but we want to treat them as two separate cards, so we need to split them up
def split_dfc(card):
    face = 0
    while face < 2:
        card['illustration_id'] = card['card_faces'][face]['illustration_id']
        card['name'] = card['card_faces'][face]['name']
        if card['card_faces'][face].get('flavor_name'):
            card['flavor_name'] = card['card_faces'][face]['flavor_name']
        card['mana_cost'] = card['card_faces'][face]['mana_cost']
        card['type_line'] = card['card_faces'][face]['type_line']
        card['oracle_text'] = card['card_faces'][face]['oracle_text']
        card['colors'] = card['card_faces'][face]['colors']
        if card['card_faces'][face].get('power'):
            card['power'] = card['card_faces'][face]['power']
        if card['card_faces'][face].get('toughness'):
            card['toughness'] = card['card_faces'][face]['toughness']
        card['artist'] = card['card_faces'][face]['artist']
        card['image_uris'] = card['card_faces'][face]['image_uris']
        save_card_main(card)
        face += 1
         
#clean up the data we're saving so the AI can use it
#remove curly brackets, convert long dash to hyphen
def clean_data(data):
    data = str(data)
    data = data.replace('{', '')
    data = data.replace('}', '')
    data = data.replace('—', '-')
    data = data.replace('—', "-")
    #remove placeholder text
    data = data.replace('WATERMARK_PLACEHOLDER', '')
    data = data.replace('SECURITY_STAMP_PLACEHOLDER', '')
    data = data.replace('POWER_PLACEHOLDER', '')
    data = data.replace('TOUGHNESS_PLACEHOLDER', '')
    data = data.replace('KEYWORDS_PLACEHOLDER', '')
    data = data.replace('PROMO_TYPES_PLACEHOLDER', '')
    data = data.replace('SPOTLIGHT_PLACEHOLDER', '')
    #remove double commas
    data = data.replace(', ,', ',')
    #remove ( and )
    data = data.replace('(', '')
    data = data.replace(')', '')
    #remove square brackets
    data = data.replace('[', '')
    data = data.replace(']', '')
    #remove single quotes
    data = data.replace('\'', '')
    #remove double quotes
    data = data.replace('"', '')
    #remove any " , " that might be left over
    #data = data.replace(' , ', '')
    #remove double commas
    data = data.replace(',,', '')
    #remove /,
    data = data.replace('/,', '')
    #remove " ,"
    data = data.replace(' ,', ' ')
    #remove double spaces
    data = data.replace('  ', ' ')
    #replace ǵ with g
    data = data.replace('ǵ', 'g')
    #replace õ with o
    data = data.replace('õ', 'o')
    #replace é with e
    data = data.replace('é', 'e')
    #replace ï with i
    data = data.replace('ï', 'i')
    #replace ñ with n
    data = data.replace('ñ', 'n')
    #replace ë with e
    data = data.replace('ë', 'e')
    #replace û with u
    data = data.replace('û', 'u')
    #replace ó with o
    data = data.replace('ó', 'o')
    #replace ń with n
    data = data.replace('ń', 'n')
    #put ' back in for the placeholder `
    data = data.replace('`', '\'')
    return data

#open the JSON file and load the data
with open(json_filename, 'r', encoding="utf8") as f:
    card_data = json.load(f)
    #loop through each card in the data, one by one, and save the image and data
for card in card_data:
    #figure out if we're working with a double-faced card or a split card - we have a special function for those
    if card['layout'] == 'transform' or card['layout'] == 'modal_dfc' or card['layout'] == 'reversible_card' or card['layout'] == 'double_faced_token':
        split_dfc(card)
    #if the layout is art_series, skip it, we don't want to save those
    elif card['layout'] == 'art_series':
        continue
    else: save_card_main(card)