anidb-series-embeddings / raw_xml_transformer.py
Cameron Yan
Add raw XML downloader and trasformer script.
d00753c
raw
history blame
1.27 kB
import os
import gzip
import requests
import xml.etree.ElementTree as ET
from datetime import datetime
os.makedirs('./tmp', exist_ok=True)
url = "https://anidb.net/api/anime-titles.xml.gz"
cache_file = './last_downloaded.txt'
if not os.path.exists(cache_file) or datetime.strptime(open(cache_file).read(), "%Y-%m-%d").date() != datetime.now().date():
response = requests.get(url, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
})
# write out the gzipped file
with open('./tmp/anime-titles.xml.gz', 'wb') as f:
f.write(response.content)
# update cache file
with open(cache_file, 'w') as f:
f.write(datetime.now().strftime("%Y-%m-%d"))
with gzip.open('./tmp/anime-titles.xml.gz', 'rb') as f:
file_content = f.read()
root = ET.fromstring(file_content)
with open('./raw/anime-titles.csv', 'w') as f:
for anime in root.findall('anime'):
aid = anime.get('aid')
for title in anime.findall('title'):
type_ = title.get('type')
lang = title.attrib['{http://www.w3.org/XML/1998/namespace}lang']
title_text = title.text.replace("|", "") # clean any pipes out of the title
f.write(f'{aid}|{type_}|{lang}|{title_text}\n')