Uh oh!
There was an error while loading. Please reload this page.
This repository was archived by the owner on May 20, 2026. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb_setup.py
More file actions
Latest commit
192 lines (161 loc) · 6.78 KB
/
Copy pathdb_setup.py
File metadata and controls
192 lines (161 loc) · 6.78 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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
importos.path
importjson
importsys
importtime
importargparse
importuuid
importpymongo
importdatetime
args= {}
client=None
gwentDB=None
SOURCE_FOLDER="./"
FILES= {"rarities": SOURCE_FOLDER+"rarities.jsonl", "groups": SOURCE_FOLDER+"groups.jsonl",
"factions": SOURCE_FOLDER+"factions.jsonl", "categories": SOURCE_FOLDER+"categories.jsonl"}
CARDS_FILE=SOURCE_FOLDER+"cards.jsonl"
# Set the command line parameters.
defset_parser():
parser=argparse.ArgumentParser(description='This script allows you to perform the initial seed '
'for the gwentapi db.')
parser.add_argument('-f', '--force', help='Disable safeguards and force the database to be dropped'
'before the insertion of the data.',
action='store_true', required=False)
parser.add_argument('-u', '--username', help='Username used for authentication')
parser.add_argument('-p', '--password', help='Indicate that a password is needed for the authenticated user.'
'Will start an interactive prompt.', action='store_true')
parser.add_argument('--host', help='The host to connect to.')
parser.add_argument('--port', help='Port to connect to.')
parser.add_argument('--authenticationDatabase', help='Database to authenticate to. Where your user account '
'was created.')
globalargs
args=parser.parse_args()
defis_insert_safe():
collections=gwentDB.collection_names(include_system_collections=False)
forcollection, pathinFILES.items():
ifcollectionincollections:
returnFalse
if"cards"incollections:
returnFalse
if"variations"incollections:
returnFalse
returnTrue
definsertUUID(item):
id=uuid.uuid4().bytes
item["uuid"] =id
deftestIfFileExists():
forkey, pathinFILES.items():
ifnotos.path.isfile(path):
print("Error: "+path+" doesn't exists.")
returnFalse
returnTrue
defdrop_collections(collection):
print("Dropping the '"+collection+"' collection.")
gwentDB[collection].drop()
defmongodb_conn():
try:
ifargs.hostandargs.port:
returnpymongo.MongoClient(args.host, args.port)
elifargs.host:
returnpymongo.MongoClient(args.host)
else:
returnpymongo.MongoClient()
exceptpymongo.errors.ConnectionFailurease:
print("Could not connect to the server: %s"%e)
# Untested on other platforms other than Linux.
defgetpass():
password=""
ifsys.platform!="win32":
os.system("stty -echo")
password=input("Enter Password: ")
os.system("stty echo")
print("")
else:
password=input("Enter Password: ")
returnpassword
defmongodb_auth():
try:
ifargs.passwordandargs.usernameandargs.authenticationDatabase:
password=getpass()
client.gwentapi.authenticate(args.username, password, source=args.authenticationDatabase)
elifargs.passwordandargs.username:
password=getpass()
client.gwentapi.authenticate(args.username, password)
returnTrue
exceptpymongo.errors.OperationFailurease:
print("Error: %s"%e)
returnFalse
defmain():
globalgwentDB
globalclient
client=mongodb_conn()
gwentDB=client.gwentapi
ifnotmongodb_auth():
return
ifnottestIfFileExists():
return
ifnotargs.forceandnotis_insert_safe():
print("The database already contain some collections.")
print("The operation was aborted.")
return
forcollection, pathinFILES.items():
print("Working on: "+collection)
drop_collections(collection)
withopen(path, encoding="utf-8", newline="\n") asf:
forlineinf:
data=json.loads(line)
insertUUID(data)
data['last_modified'] =datetime.datetime.utcnow()
gwentDB[collection].insert_one(data)
gwentDB[collection].create_index([('name', pymongo.ASCENDING)], unique=True)
gwentDB[collection].create_index([('uuid', pymongo.ASCENDING)], unique=True)
# Processing cards
print("Working on: cards")
drop_collections("cards")
drop_collections("variations")
withopen(CARDS_FILE, encoding="utf-8", newline="\n") asf:
forlineinf:
data=json.loads(line)
forvariationindata["variations"]:
variation["art"]["fullsizeImage"] =data["key"] +"_full.png"
variation["art"]["thumbnailImage"] =data["key"] +"_thumbnail.png"
data.pop("key", None)
# Manual reference for faction
if"faction"indata:
faction_id=gwentDB.factions.find_one({"name": data["faction"]})["_id"]
data["faction_id"] =faction_id
# Renaming type to group until the jsonl format change.
# Manual reference for group
if"type"indata:
data["group"] =data.pop("type")
group_id=gwentDB.groups.find_one({"name": data["group"]})["_id"]
data["group_id"] =group_id
if"categories"indata:
categories_id=list()
forcategoryindata["categories"]:
category_id=gwentDB.categories.find_one({"name": category})["_id"]
categories_id.append(category_id)
data["categories_id"] =categories_id
insertUUID(data)
data['last_modified'] =datetime.datetime.utcnow()
variations=data.pop("variations")
card_id=gwentDB.cards.insert_one(data).inserted_id
forvariationinvariations:
if"rarity"invariation:
rarity_id=gwentDB.rarities.find_one({"name": variation["rarity"]})["_id"]
variation["rarity_id"] =rarity_id
variation["card_id"] =card_id
insertUUID(variation)
variation['last_modified'] =datetime.datetime.utcnow()
gwentDB.variations.insert_many(variations)
gwentDB.cards.create_index([('name', pymongo.ASCENDING)], unique=True)
gwentDB.cards.create_index([('uuid', pymongo.ASCENDING)], unique=True)
gwentDB.variations.create_index([('card_id', pymongo.ASCENDING)])
gwentDB.variations.create_index([('uuid', pymongo.ASCENDING)])
if__name__=='__main__':
set_parser()
print("Starting")
start=time.time()
main()
print("Elapsed Time: %s"% (time.time() -start))