aboutsummaryrefslogtreecommitdiff
path: root/parser/scrapeToJson.py
blob: 5eacb5adb304b0b7d13a2fafa2d5200f8abc1e66 (plain)
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
#!/usr/bin/env python3
import json
import re
import utils
import attacks

class Creature(dict):
    def getBonus(self, ability):
        return (self['stats'][ability] - 10) // 2

def processMonster(data, weapons, armors, spells):
    names2names = {'ac': 'Armor Class', 'hp': 'Hit Points', 'speed': 'Speed', 'saves': 'Saving Throws', 'd_resistances': 'Damage Resistances?', 'd_vulnerabilities': 'Damage Vulnerabilities', 'd_immunities': 'Damage Immunities', 'c_immunities': 'Condition Immunities', 'senses': 'Senses', 'langs': 'Languages', 'skills': 'Skills'}
    desc = Creature()
    desc['entry'] = 'creatures'
    for name in names2names:
        m = re.search('(\*\*{}\.?\*\*)(.*)'.format(names2names[name]), data)
        if m:
            desc[name] = m.group(2).strip()
        else:
            desc[name] = ""
    for name in ['d_resistances', 'd_vulnerabilities', 'd_immunities', 'c_immunities']:
        # Formatted a, b, c[; d, e, and f from nonmagical attacks[ that aren't g]]
        # Blerg. Also can be "not made with g weapons"
        # Maybe without the a, b, c part
        parts = [desc[name]]
        if '; ' in desc[name]:
            parts = desc[name].split('; ')
        desc[name] = []
        for part in parts:
            part = part.strip().lower()
            # Look for "nonmagical", and "that aren't x"
            qualifiers = []
            if 'nonmagical' in part:
                qualifiers.append('nonmagical')
            if 'that aren\'t' in part:
                qualifiers.append('non-' + re.search('(?<=that aren\'t ).*$', part).group(0))
            if 'not made with ' in part:
                qualifiers.append('non-' + re.search('(?<=not made with )\w*', part).group(0))
            for typ in re.findall('([a-z]+(?=,)|^[a-z]+$|(?<=, )[a-z]+$|(?<=and )[a-z]+(?= from)|(?<=and )[a-z]+(?= \(from))', part):
                desc[name].append({'type': typ, 'qualifiers': qualifiers})
    # Calc things about hp
    hitdieMatch = re.search('(\d+)d(\d+)', desc['hp'])
    desc['hit_die_count'] = int(hitdieMatch.group(1))
    desc['hit_die_sides'] = int(hitdieMatch.group(2))
    del desc['hp']
    desc['name'] = re.search('(?<=name: ).*', data).group(0).strip()
    desc['type'] = re.search('(?<=type: ).*', data).group(0).strip()
    desc['cr'] = float(re.search('(?<=cr: ).*', data).group(0).strip())
    description = re.search('(?<=_).*(?=_)', data).group(0).strip()
    desc['size'] = description.split(' ')[0]
    desc['alignment'] = description.split(', ')[-1]
    desc['stats'] = {ability: int(score.strip().split(' ')[0]) for ability, score in zip(['str', 'dex', 'con', 'int', 'wis', 'cha'], re.findall('(?<=\|) *\d.*?(?=\|)', data))}
    desc['inventory'] = [] # Fill with weapons and armor
    desc['observant'] = False # maybe set to true later
    # Add a few null-valued items that will be set when the creature is first generated
    desc['givenName'] = 'NAME'
    desc['hpMax'] = -1
    desc['hp'] = -1
    # Modify ac stuff
    desc['natural_armor'] = {'name': '', 'bonus': 0}
    correctAC = int(desc['ac'].split(' ')[0] if ' ' in desc['ac'] else desc['ac'])
    natural = ''
    armorBonus = 0
    armor = re.search('(?<=\().*(?=\))', desc['ac'])
    if armor:
        armor = armor.group(0).lower()
        if ',' in armor:
            armor = armor.split(',')
        else:
            armor = [armor]
        for a in armor:
            a = a.strip()
            # If it has "armor" in it, remove that
            a = re.search('^(.*?)(?: armor)?$', a).group(1)
            #print('Working with {}'.format(a))
            if a == 'natural' or a == 'patchwork' or 'scraps' in a:
                natural = a
                continue
            if 'with' in a:
                continue
            # Search for it in armors
            found = False
            for armorDict in armors:
                if armorDict['name'] == a:
                    found = True
                    bonus = armorDict['ac']
                    typ = armorDict['armor_type']
                    #desc['inventory'].append(armorDict)
                    desc['inventory'].append({'entry': 'item', 'name': a, 'type': 'armor', 'text': '{} armor'.format(a)})
                    break
            if not found:
                print('Cound not identify armor: {}'.format(a))
                continue
            #else:
            #    print('Found {} armor {} (bonus = {})'.format(typ, name, bonus))
            if typ == 'light':
                armorBonus = bonus + desc.getBonus('dex')
            elif typ == 'medium':
                armorBonus = bonus + min(2, desc.getBonus('dex'))
            elif typ == 'heavy':
                armorBonus = bonus
            elif typ == 'misc' or typ == 'shield':
                armorBonus += bonus
    if armorBonus == 0 and not natural: # Got through all that and came up dry
        armorBonus = 10 + desc.getBonus('dex')
    if natural:
        desc['natural_armor'] = {'name': natural, 'bonus': correctAC - armorBonus}
    elif armorBonus != correctAC:
        print('Got a bad result for {}: armor string is {}, but we calculated {}'.format(desc['name'], desc['ac'], armorBonus))
    del desc['ac']

    # Search for a description section
    desc['text'] = ''
    description = re.search('(?s)(?<={}).*?(?=###|$)'.format('### Description'), data)
    if description:
        desc['text'] = description.group(0).strip()
    else:
        # Try looking for the last entry (**something**) with an empty line and then one or more paragraphs before end of file
        description = re.search('(?s)(?<=\*\*).*\n\n(.*?)(?=###|$)', data)
        if description:
            #print(f'Found description without a header for {desc["name"]}')
            desc['text'] = description.group(1).strip()

    # Next do sections
    names2sectHeads = {'feature': '\*\*Challenge\*\*', 'action': '### Actions', 'legendary_action': '### Legendary Actions', 'reaction': '### Reactions'}
    # We put them all in "features" list
    desc['features'] = []
    for name in names2sectHeads:
        section = re.search('(?s)(?<={}).*?(?=###|$)'.format(names2sectHeads[name]), data)
        if section:
            # There might be a special section text as the first new line after the header
            #text = re.match('(?s)(\s*\w[^\*].*?)([\r\n]+[\*#]|$)', '\n'.join(section.group(0).split('\n')[1:]))
            #if text and re.search('\w', text.group(1)):
            #    desc[name]['_text'] = text.group(1).strip()
            for m in re.findall('(?s)\n\*\*(.*?)\.?\*\*(.*?)(?=\n\*\*|\n\n|$)', section.group(0)):
                desc['features'].append({'entry': 'feature', 'name': m[0].lower(), 'text': m[1].strip(), 'type': name})
    # Next, simplify and codify a few things
    # Guess the proficiency bonus
    desc['prof'] = int(max(0, (desc['cr']-1) // 4) + 2)
    # Now convert skills, saves, and attacks to be based on proficiency and abilities rather than raw numbers
    skillStr = desc['skills']
    desc['skills'] = {} # Map skill to plurality of proficiency
    if skillStr:
        for skill in skillStr.split(','):
            skillName, skillBonus, ability = utils.procSkill(skill)
            abilityBonus = desc.getBonus(ability)
            profTimes = (skillBonus - abilityBonus) / desc['prof']
            if round(profTimes) != profTimes:
                print('Things came out funny for {}; skill {} has bonus {}, but proficiency is {} and the relevant ability ({}) gets {}'.format(desc['name'], skillName, skillBonus, desc['prof'], ability, desc.getBonus(ability)))
            desc['skills'][skillName] = round(profTimes)
    savesStr = desc['saves']
    desc['saves'] = []
    if savesStr:
        for save in savesStr.split(', '):
            ability = save.split(' ')[0].lower()
            if int(save.split('+')[1]) != desc.getBonus(ability) + desc['prof']:
                print('Things came out funny for {}; {} save has bonus {}, but proficiency is {} and the relevant ability ({}) gets {}'.format(desc['name'], ability, int(save.split('+')[1]), desc['prof'], ability, desc.getBonus(ability)))
            desc['saves'].append(ability)
    for action in desc['features']:
        if re.match('.*Attack:', action['text']):
            attacks.procAttackAction(desc, action, weapons)
        elif 'spellcasting' in action['name']:
            attacks.procSpellAction(desc, action, spells)

    # Remove weapon actions from features (they were just added to inventory)
    desc['features'] = [a for a in desc['features'] if 'attack' not in a or a['attack']['weapon_type'] == 'unknown']
    # Get rid of precalculated passive perception
    # It's always the last item in senses
    passivePercep = int(desc['senses'].split(' ')[-1])
    shouldBe = 10 + desc.getBonus('wis')
    if 'Perception' in desc['skills']:
        shouldBe += desc['skills']['Perception'] * desc['prof']
    if passivePercep != shouldBe:
        if(passivePercep - 5 == shouldBe):
            desc['observant'] = True
        else:
            print('Passive perception didn\'t come out right for {}: is {}, but should be {}'.format(desc['name'], passivePercep, shouldBe))
    desc['senses'] = desc['senses'].split(', ')[:-1]
    return desc

from pathlib import Path
weapons = utils.getWeapons()
armors = utils.getArmor()
spells = utils.getSpells()

def dumpStuff(stuff, destDir):
    Path(destDir).mkdir(parents=True, exist_ok=True)
    for thing in stuff:
        with open(destDir + '/' + thing['name'].replace(' ', '_').replace('/', '') + '.json', 'w') as f:
            json.dump(thing, f, indent=2)

dumpStuff(weapons, 'parsed/weapons/')
dumpStuff(armors, 'parsed/armor/')
dumpStuff(spells, 'parsed/spells/')

for monster in Path(utils.docsLoc + '/gamemaster_rules/monsters/').glob('*.md'):
    #print('Processing {}'.format(monster))
    if monster.name == 'index.md':
        continue
    with monster.open() as f:
        data = f.read()
    Path('parsed/creatures/').mkdir(exist_ok=True)
    with open('parsed/creatures/' + monster.stem + '.json', 'w') as f:
        json.dump(processMonster(data, weapons, armors, spells), f, indent=2)