-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmake_freequest.py
More file actions
204 lines (173 loc) · 6.73 KB
/
make_freequest.py
File metadata and controls
204 lines (173 loc) · 6.73 KB
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
# 恒常フリクエ・修練場のCSVデータをJSONファイルに変換
import json
from pathlib import Path
import csv
import unicodedata
import dataclasses
from typing import List
from tqdm import tqdm
import argparse
import logging
import requests
logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s')
logger = logging.getLogger(__name__)
freequest_file = Path(__file__).resolve().parent / Path("freequest.csv")
freequest_json_file = Path(__file__).resolve().parent \
/ "data/json" / Path("freequest.json")
drop_file = Path(__file__).resolve().parent / Path("hash_drop.json")
url = "https://api.atlasacademy.io/export/JP/nice_war.json"
with open(drop_file, encoding='UTF-8') as f:
drop_item = json.load(f)
# FGOData_path = "../FGOData"
# if Path(FGOData_path).exists() is False:
# FGOData_path = "../../FGOData"
# viewQuestInfo_file = Path(FGOData_path) / "JP_tables/quest/viewQuestInfo.json"
# with open(viewQuestInfo_file) as f:
# quest_info = json.load(f)
name2item = {}
shortname2name = {item["shortname"]: item["name"] for item in drop_item if "shortname" in item.keys()}
shortname2id = {item["shortname"]: item["id"] for item in drop_item if "shortname" in item.keys()}
shortname2dropPriority = {item["shortname"]: item["dropPriority"] for item in drop_item if "shortname" in item.keys()}
id2name = {item["id"]: item["name"] for item in drop_item if "name" in item.keys()}
id2type = {item["id"]: item["type"] for item in drop_item if "type" in item.keys()}
id2dropPriority = {item["id"]: item["dropPriority"] for item in drop_item if "dropPriority" in item.keys()}
# questId2dropItemNum = {quest["questId"]: quest["dropSvtNum"] + quest["dropItemNum"] for quest in quest_info}
alias2id = {}
for item in drop_item:
alias2id[unicodedata.normalize('NFKC', item["name"])] = item["id"]
if "shortname" in item.keys():
alias2id[unicodedata.normalize('NFKC', item["shortname"])] = item["id"]
if "alias" in item.keys():
for a in item["alias"]:
alias2id[unicodedata.normalize('NFKC', a)] = item["id"]
class APIError(Exception):
"""
API 呼び出しが失敗したことを示すエラー
"""
@dataclasses.dataclass(frozen=True)
class DropItem:
"""
クエストのドロップアイテム
"""
id: int
name: str
type: str
dropPriority: int
@dataclasses.dataclass(frozen=True)
class FgoQuest:
"""
クエスト情報
"""
id: int
name: str
place: str
chapter: str
category: str
qp: int
drop: List[DropItem]
dropItemNum: int
@dataclasses.dataclass(frozen=True)
class FgoFreeQuest(FgoQuest):
scPriority: int
scName: str
def fetch_free_quests(url: str) -> dict:
"""
指定されたURLからJSONを取得し、"type"が"free"のクエストを抽出。
結果を {id: {"name": ..., "recommendLv": ...}} の形式で返す。
"""
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
result = {}
for entry in data: # 辞書A
spots = entry.get("spots", [])
for spot in spots: # 辞書B
if isinstance(spot, dict):
quests = spot.get("quests", [])
for quest in quests: # 辞書D
if isinstance(quest, dict):
quest_id = quest.get("id")
if quest_id is not None:
result[quest_id] = {
"name": quest.get("name"),
"recommendLv": quest.get("recommendLv")
}
return result
except requests.exceptions.RequestException as e:
raise RuntimeError(f"HTTPエラー: {e}")
except ValueError as e:
raise RuntimeError(f"JSON解析エラー: {e}")
def main(args):
with open(freequest_file, encoding='utf-8-sig') as f:
reader = csv.DictReader(f)
tmps = [row for row in reader]
free_quests = fetch_free_quests(url)
quest_output = []
for tmp in tqdm(tmps):
# ドロップを作成
drop = []
for item in tmp.keys():
if item.startswith("item"):
if tmp[item] != "":
try:
item_id = shortname2id[tmp[item]]
except:
logger.critical('item: %s', item)
logger.critical('tmp[item]: %s', tmp[item])
exit()
name = id2name[item_id]
drop.append(DropItem(item_id, name, id2type[item_id],
id2dropPriority[item_id]))
drop = sorted(drop, key=lambda x: x.dropPriority, reverse=True)
questId = int(tmp["id"])
quest = free_quests[questId]
if quest["recommendLv"] == "90++":
qp = int((90*100+400)*20*1.2*1.2) # 270,720
elif quest["recommendLv"] == "90+":
qp = int((90*100+400)*20*1.2) # 225,600
elif quest["recommendLv"] == "90★":
qp = 324870
elif quest["recommendLv"] == "90★★":
qp = 389850
elif quest["recommendLv"] == "100":
qp = 32487
elif quest["recommendLv"] == "100+":
qp = 34761
elif quest["recommendLv"] == "100++":
qp = 37194
elif quest["recommendLv"] == "100+++":
qp = 39798
elif quest["recommendLv"] == "100★":
qp = 42584
elif quest["recommendLv"] == "100★★":
qp = 45565
elif quest["recommendLv"] == "100★★★":
qp = 48754
else:
qp = int((int(quest["recommendLv"])*100 + 400)*1.3)
freequest = FgoFreeQuest(questId, tmp["quest"], tmp["place"],
tmp["chapter"], tmp["category"], qp, drop,
-1,
int(tmp['scPriority']),
tmp["scName"])
questname = quest["name"]
if tmp["quest"] != questname:
logger.warning("場所名が異なります%s %s", tmp["quest"], questname)
quest_output.append(dataclasses.asdict(freequest))
with open(freequest_json_file, "w", encoding='UTF-8') as f:
f.write(json.dumps(quest_output, ensure_ascii=False, indent=4))
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'--loglevel',
choices=('DEBUG', 'INFO', 'WARNING'),
default='WARNING',
help='loglevel [default: WARNING]',
)
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
logger.setLevel(args.loglevel)
main(args)