Files
blitz-tools/extract_tankopedia.py
T

231 lines
9.2 KiB
Python
Raw Normal View History

2021-01-25 09:26:57 +02:00
#!/usr/bin/env python3
## PYTHON VERSION MUST BE 3.7 OR HIGHER
2018-10-01 12:17:54 +08:00
# Extract tankopedia data in WG API JSON format from Blitz app files (Android APK unzipped)
2022-08-18 09:42:55 +03:00
from os import path
2020-03-26 16:26:43 +02:00
import sys, argparse, json, os, inspect, aiohttp, asyncio, aiofiles, re, logging, time, xmltodict, collections, configparser
2018-10-04 11:24:24 +08:00
import blitzutils as bu
2018-10-03 23:17:27 +08:00
from blitzutils import WG
2018-10-01 12:17:54 +08:00
logging.getLogger("asyncio").setLevel(logging.DEBUG)
2020-03-26 16:26:43 +02:00
FILE_CONFIG = 'blitzstats.ini'
2022-08-18 09:42:55 +03:00
# BLITZAPP_STRINGS='/assets/Data/Strings/en.yaml'
# BLITZAPP_VEHICLES_DIR='/assets/Data/XML/item_defs/vehicles/'
BLITZAPP_STRINGS='Data/Strings/en.yaml'
BLITZAPP_VEHICLES_DIR='Data/XML/item_defs/vehicles/'
BLITZAPP_VEHICLE_FILE='list.xml'
2018-10-01 12:17:54 +08:00
2018-10-04 11:24:24 +08:00
wg = None
2018-10-01 12:17:54 +08:00
## main() -------------------------------------------------------------
async def main(argv):
2018-10-04 11:24:24 +08:00
global wg
2019-12-17 21:25:54 +02:00
# set the directory for the script
os.chdir(os.path.dirname(sys.argv[0]))
2020-03-26 16:26:43 +02:00
## Read config
BLITZAPP_FOLDER = '.'
try:
if os.path.isfile(FILE_CONFIG):
config = configparser.ConfigParser()
config.read(FILE_CONFIG)
2020-03-26 16:26:43 +02:00
configOptions = config['EXTRACT_TANKOPEDIA']
BLITZAPP_FOLDER = configOptions.get('blitz_app_dir', BLITZAPP_FOLDER)
except:
pass
2018-10-01 12:17:54 +08:00
parser = argparse.ArgumentParser(description='Extract Tankopedia data from Blitz game files')
2020-03-26 16:26:43 +02:00
parser.add_argument('blitz_app_base', type=str, nargs='?', metavar="BLITZAPP_FOLDER", default=BLITZAPP_FOLDER, help='Base dir of the Blitz App files')
parser.add_argument('tanks', type=str, default='tanks.json', nargs='?', metavar="TANKS_FILE", help='File to write Tankopedia')
parser.add_argument('maps', type=str, default='maps.json', nargs='?', metavar='MAPS_FILE', help='File to write map names')
arggroup = parser.add_mutually_exclusive_group()
arggroup.add_argument('-d', '--debug', action='store_true', default=False, help='Debug mode')
arggroup.add_argument('-v', '--verbose', action='store_true', default=False, help='Verbose mode')
arggroup.add_argument('-s', '--silent', action='store_true', default=False, help='Silent mode')
2018-10-01 12:17:54 +08:00
args = parser.parse_args()
2019-12-24 12:30:09 +02:00
bu.set_log_level(args.silent, args.verbose, args.debug)
2018-10-01 12:17:54 +08:00
2018-10-04 11:24:24 +08:00
wg = WG()
2018-10-01 12:17:54 +08:00
tasks = []
2020-11-27 00:00:00 +02:00
for nation in wg.NATION:
tasks.append(asyncio.create_task(extract_tanks(args.blitz_app_base, nation)))
2018-10-01 12:17:54 +08:00
tanklist = []
for tanklist_tmp in await asyncio.gather(*tasks):
tanklist.extend(tanklist_tmp)
tank_strs, map_strs = await read_user_strs(args.blitz_app_base)
2018-10-02 14:40:41 +08:00
2019-01-29 10:35:35 +02:00
json_data = None
userStrs = {}
tanks = {}
if os.path.exists(args.tanks):
try:
async with aiofiles.open(args.tanks) as infile:
json_data = json.loads(await infile.read())
userStrs = json_data['userStr']
tanks = json_data['data']
except Exception as err:
bu.error('Unexpected error when reading file: ' + args.tanks + ' : ' + str(err))
2018-10-04 11:24:24 +08:00
async with aiofiles.open(args.tanks, 'w', encoding="utf8") as outfile:
new_tanks, new_userStrs = await convert_tank_names(tanklist, tank_strs)
2019-01-29 10:35:35 +02:00
# merge old and new tankopedia
tanks.update(new_tanks)
userStrs.update(new_userStrs)
2018-10-04 11:24:24 +08:00
tankopedia = collections.OrderedDict()
2018-10-01 12:17:54 +08:00
tankopedia['status'] = 'ok'
2019-01-29 10:35:35 +02:00
tankopedia['meta'] = { "count": len(tanks) }
2021-07-15 20:22:46 +03:00
tankopedia['data'] = bu.sort_dict(tanks, number=True)
tankopedia['userStr'] = bu.sort_dict(userStrs)
bu.verbose_std('New tankopedia \'' + args.tanks + '\' contains ' + str(len(tanks)) + ' tanks')
2021-02-16 11:58:41 +02:00
bu.verbose_std('New tankopedia \'' + args.tanks + '\' contains ' + str(len(userStrs)) + ' tank strings')
2018-10-02 20:58:36 +08:00
await outfile.write(json.dumps(tankopedia, ensure_ascii=False, indent=4, sort_keys=False))
2018-10-02 14:40:41 +08:00
2018-10-04 11:24:24 +08:00
if args.maps != None:
2019-01-29 10:35:35 +02:00
maps = {}
if os.path.exists(args.maps):
try:
async with aiofiles.open(args.maps) as infile:
maps = json.loads(await infile.read())
except Exception as err:
bu.error('Unexpected error when reading file: ' + args.maps + ' : ' + str(err))
# merge old and new map data
maps.update(map_strs)
2018-10-04 11:24:24 +08:00
async with aiofiles.open(args.maps, 'w', encoding="utf8") as outfile:
bu.verbose_std('New maps file \'' + args.maps + '\' contains ' + str(len(maps)) + ' maps')
2019-01-29 10:35:35 +02:00
await outfile.write(json.dumps(maps, ensure_ascii=False, indent=4, sort_keys=True))
2018-10-01 12:17:54 +08:00
return None
async def extract_tanks(blitz_app_base : str, nation: str):
2018-10-01 12:17:54 +08:00
tanks = []
2022-08-18 09:42:55 +03:00
# WG has changed the location of Data directory - at least in steam client
if path.isdir(path.join(blitz_app_base, 'assets')):
blitz_app_base = path.join(blitz_app_base, 'assets')
list_xml_file = path.join(blitz_app_base, BLITZAPP_VEHICLES_DIR ,nation ,BLITZAPP_VEHICLE_FILE)
if not path.isfile(list_xml_file):
2018-10-01 12:17:54 +08:00
print('ERROR: cannot open ' + list_xml_file)
return None
2018-10-04 11:24:24 +08:00
bu.debug('Opening file: ' + list_xml_file + ' (Nation: ' + nation + ')')
async with aiofiles.open(list_xml_file, 'r', encoding="utf8") as f:
2018-10-01 12:17:54 +08:00
try:
tankList = xmltodict.parse(await f.read())
for data in tankList['root'].keys():
tank_xml = tankList['root'][data]
2021-02-16 11:58:41 +02:00
tank = dict()
2018-10-01 12:17:54 +08:00
tank['is_premium'] = issubclass(type(tank_xml['price']), dict)
2021-04-29 00:09:40 +03:00
tank['nation'] = nation
tank['tank_id'] = await get_tank_id(nation, int(tank_xml['id']))
tank['tier'] = int(tank_xml['level'])
tank['type'] = await get_tank_type(tank_xml['tags'])
2021-04-29 00:09:40 +03:00
tank['userStr'] = tank_xml['userString']
2021-02-16 12:02:31 +02:00
#bu.debug('Reading tank string: ' + tank['userStr'], force=True)
2018-10-01 12:17:54 +08:00
tanks.append(tank)
except Exception as err:
2018-10-04 11:24:24 +08:00
bu.error(err)
2018-10-01 12:17:54 +08:00
sys.exit(2)
return tanks
async def read_user_strs(blitz_app_base : str) -> dict:
2018-10-02 14:40:41 +08:00
"""Read user strings to convert map and tank names"""
tank_strs = {}
map_strs = {}
2022-08-18 09:42:55 +03:00
filename = path.join(blitz_app_base, BLITZAPP_STRINGS)
2018-10-04 11:24:24 +08:00
bu.debug('Opening file: ' + filename + ' for reading UserStrings')
2018-10-01 12:17:54 +08:00
try:
async with aiofiles.open(filename, 'r', encoding="utf8") as f:
2018-10-02 14:40:41 +08:00
p_tank = re.compile('^"(#\\w+?_vehicles:.+?)": "(.+)"$')
p_map = re.compile('^"#maps:(.+?):.+?: "(.+?)"$')
2018-10-01 12:17:54 +08:00
async for l in f:
2018-10-02 14:40:41 +08:00
m = p_tank.match(l)
if m != None:
tank_strs[m.group(1)] = m.group(2)
m = p_map.match(l)
2018-10-08 00:14:08 +08:00
if m != None and m.group(2) != 'Macragge':
2018-10-02 14:40:41 +08:00
map_strs[m.group(1)] = m.group(2)
2018-10-01 12:17:54 +08:00
except Exception as err:
2018-10-04 11:24:24 +08:00
bu.error(err)
2018-10-01 12:17:54 +08:00
sys.exit(1)
2018-10-02 14:40:41 +08:00
return tank_strs, map_strs
async def convert_tank_names(tanklist : list, tank_strs: dict) -> dict:
2018-10-02 14:40:41 +08:00
"""Convert tank names for Tankopedia"""
tankopedia = {}
userStrs = {}
2018-10-04 11:24:24 +08:00
2018-10-02 14:40:41 +08:00
try:
for tank in tanklist:
tank['name'] = tank_strs[tank['userStr']]
2021-02-16 11:58:41 +02:00
#userStrs[tank['userStr'].split(':')[1]] = tank['name']
2018-10-02 14:40:41 +08:00
tank.pop('userStr', None)
2021-04-29 00:09:40 +03:00
tank_tmp = collections.OrderedDict()
for key in sorted(tank.keys()):
tank_tmp[key] = tank[key]
tankopedia[str(tank['tank_id'])] = tank_tmp
2018-10-02 20:58:36 +08:00
2021-02-16 11:58:41 +02:00
for tank_str in tank_strs:
skip = False
key = tank_str.split(':')[1]
bu.debug('Tank string: ' + key + ' = ' + tank_strs[tank_str])
re_strs = [r'^Chassis_', r'^Turret_', r'^_', r'_short$' ]
for re_str in re_strs:
p = re.compile(re_str)
if p.match(key):
skip = True
break
if skip:
continue
userStrs[key] = tank_strs[tank_str]
2018-10-04 11:24:24 +08:00
# sorting
2018-10-02 20:58:36 +08:00
tankopedia_sorted = collections.OrderedDict()
2018-10-04 11:24:24 +08:00
for tank_id in sorted(tankopedia.keys(), key=int):
2018-10-02 20:58:36 +08:00
tankopedia_sorted[str(tank_id)] = tankopedia[str(tank_id)]
2018-10-04 11:24:24 +08:00
userStrs_sorted = collections.OrderedDict()
for userStr in sorted(userStrs.keys()):
userStrs_sorted[userStr] = userStrs[userStr]
2021-02-16 11:58:41 +02:00
# bu.debug('Tank strings: ' + str(len(userStrs_sorted)))
2018-10-04 11:24:24 +08:00
2018-10-02 14:40:41 +08:00
except Exception as err:
2018-10-04 11:24:24 +08:00
bu.error(err)
2018-10-02 14:40:41 +08:00
sys.exit(1)
2018-10-04 11:24:24 +08:00
return tankopedia_sorted, userStrs_sorted
2018-10-01 12:17:54 +08:00
async def get_tank_id(nation: str, tank_id : int) -> int:
return (tank_id << 8) + (wg.NATION_ID[nation] << 4) + 1
2018-10-01 12:17:54 +08:00
async def get_tank_type(tagstr : str):
2018-10-01 12:17:54 +08:00
tags = tagstr.split(' ')
for t_type in wg.TANK_TYPE:
2018-10-01 12:17:54 +08:00
if tags[0] == t_type:
return t_type
return None
### main()
if __name__ == "__main__":
# To avoid 'Event loop is closed' RuntimeError due to compatibility issue with aiohttp
if sys.platform.startswith("win") and sys.version_info >= (3, 8):
try:
from asyncio import WindowsSelectorEventLoopPolicy
except ImportError:
pass
else:
if not isinstance(asyncio.get_event_loop_policy(), WindowsSelectorEventLoopPolicy):
asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())
#asyncio.run(main(sys.argv[1:]), debug=True)
asyncio.run(main(sys.argv[1:]))