Repository navigation
Expand file tree
/
Copy pathgui_local_slot_editing.py
More file actions
593 lines (568 loc) · 22.9 KB
/
Copy pathgui_local_slot_editing.py
File metadata and controls
593 lines (568 loc) · 22.9 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
"""This script provides a GUI for downloading an OSW instances page slots, editing
them locally and uploading them again."""
import json
import os
import re
# import yaml
from pathlib import Path
from typing import Union
import PySimpleGUI as psg
from numpy import array as np_array
import osw.model.page_package as package
from osw.auth import CredentialManager
from osw.express import OswExpress
from osw.wiki_tools import read_domains_from_credentials_file
from osw.wtsite import SLOTS, WtPage, WtSite
# Definition of constants
GUI_THEME = "reddit"
DEBUG = True # Set to True to get an output element in the GUI
DUMP_EMPTY_SLOTS_DEFAULT = True
SEL_INDICES_DEFAULT = [
0, # "main",
3, # "jsondata",
4, # "jsonschema",
6, # "header_template",
]
SLOTS_TO_UPLOAD_DEFAULT = np_array(list(SLOTS.keys()))[SEL_INDICES_DEFAULT].tolist()
TARGET_PAGE_DEFAULT = "https://wiki-dev.open-semantic-lab.org/wiki/Main_Page"
LWD_DEFAULT = Path(os.getcwd()).parent / "data"
SETTINGS_FILE_PATH_DEFAULT = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "settings.json"
)
CRED_FILEPATH_DEFAULT = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "accounts.pwd.yaml"
)
PACKAGE_INFO_FILE_NAME = "packages.json"
# Sub folder to store the slot content of the page in. If None, the content is stored
# in the root folder alongside the package info file.
SUB_LEVEL = None # "content"
# Whether to store the page content in a sub folder named after the namespace
NAMESPACE_AS_FOLDER = False
# Definition of functions
def str_or_none(value):
if str(value) == "" or value is None:
return "None"
else:
return str(value)
def compute_page_storage_path(
working_dir: str,
domain_str: str,
page_name_as_filename: bool,
label_str: str = None,
top_level: str = None,
) -> str:
"""Compute the folder that a page's slots are downloaded to / uploaded from.
Mirrors the folder-naming logic previously inlined in save_as_page_package: the
page label is used when 'page_name_as_filename' is set and a label is known,
otherwise the top-level page title is used. A domain sub folder is inserted so
that pages from different OSW instances don't collide inside the same local
working directory.
Both the '-DL-' (download) and '-UL-' (upload) event handlers call this helper
so they always agree on where a given page's content is stored on disk.
"""
if page_name_as_filename and label_str is not None:
page_dir_name = label_str
else:
page_dir_name = top_level
# Sanitize the domain for use as a directory name (invalid on Windows: \/:*?"<>|)
domain_dir = re.sub(r'[\\/:*?"<>|]', "_", domain_str)
return os.path.join(working_dir, domain_dir, page_dir_name)
def create_config_from_setting(settings_: dict) -> WtPage.PageDumpConfig:
config_ = WtPage.PageDumpConfig(
target_dir=settings_["local_working_directory"],
namespace_as_folder=settings_["namespace_as_folder"],
dump_empty_slots=settings_["dump_empty_slots"],
page_name_as_filename=settings_["page_name_as_filename"],
)
return config_
def save_as_page_package(
full_page_name_str,
wtsite_inst: WtSite,
dump_config_inst: WtPage.PageDumpConfig,
domain_str: str,
label_str: str = None,
top_level: str = None,
sub_level: str = None, # "content"
author: Union[str, list] = "Open Semantic World",
):
if top_level is None:
top_level = full_page_name_str.split(":")[-1]
package_repo_org = "OpenSemanticWorld-Packages"
package_repo = f"{top_level}.{sub_level}"
package_id = f"{top_level}.{sub_level}"
package_name = top_level
package_subdir = sub_level
package_branch = "deleteme"
publisher = "Open Semantic World"
working_dir = dump_config_inst.target_dir
target_dir = compute_page_storage_path(
working_dir,
domain_str,
dump_config_inst.page_name_as_filename,
label_str,
top_level,
)
if isinstance(author, list):
author_list = author
elif isinstance(author, str):
author_list = [author]
else:
author_list = [""]
if package_subdir is None:
base_url = (
f"https://raw.githubusercontent.com/{package_repo_org}/"
f"{package_repo}/{package_branch}/"
)
content_path = target_dir
else:
base_url = (
f"https://raw.githubusercontent.com/{package_repo_org}/"
f"{package_repo}/{package_branch}/{package_subdir}/"
)
content_path = os.path.join(target_dir, package_subdir)
bundle = package.PagePackageBundle(
publisher=publisher,
author=author_list,
language="en",
publisherURL=f"https://github.com/{package_repo_org}/{package_repo}",
packages={
f"{package_name}": package.PagePackage(
globalID=f"{package_id}",
label=package_name,
version="0.0.1",
description="Created by the GUI for local editing of OSW pages",
baseURL=base_url,
)
},
)
config = package.PagePackageConfig(
name=package_name,
config_path=os.path.join(target_dir, PACKAGE_INFO_FILE_NAME),
content_path=content_path,
bundle=bundle,
titles=[full_page_name_str],
)
wtsite_inst.create_page_package(
WtSite.CreatePagePackageParam(
config=config,
dump_config=dump_config_inst,
debug=False,
)
)
return {"Page package bundle": bundle, "Page package config": config}
if __name__ == "__main__":
# Predefining some variables before execution
settings_file_path = SETTINGS_FILE_PATH_DEFAULT
if os.path.exists(settings_file_path):
with open(settings_file_path) as f:
settings = json.load(f)
settings_read_from_file = True
else:
settings = {
"cred_filepath": str(CRED_FILEPATH_DEFAULT),
"local_working_directory": str(LWD_DEFAULT),
"settings_file_path": str(SETTINGS_FILE_PATH_DEFAULT),
"target_page": TARGET_PAGE_DEFAULT,
"namespace_as_folder": NAMESPACE_AS_FOLDER,
"dump_empty_slots": DUMP_EMPTY_SLOTS_DEFAULT,
"page_name_as_filename": True,
"slots_to_upload": SLOTS_TO_UPLOAD_DEFAULT,
"domain": "",
}
settings_read_from_file = False
# An empty/missing accounts.pwd.yaml must not prevent the window from opening.
# The user can still type/select a domain once the window is up.
domains, accounts, cred_load_error = [], {}, None
try:
domains, accounts = read_domains_from_credentials_file(
settings["cred_filepath"]
)
except (FileNotFoundError, ValueError) as e:
cred_load_error = f"{type(e).__name__}: {e}"
if domains:
if "wiki-dev.open-semantic-lab.org" in domains:
domain = "wiki-dev.open-semantic-lab.org"
else:
domain = domains[0]
if settings_read_from_file:
settings["domain"] = domain
else:
domain = settings.get("domain", "")
cm = CredentialManager(cred_filepath=settings["cred_filepath"])
osw_obj = None
wtsite_obj = None
if domain:
osw_obj = OswExpress(domain=domain, cred_mngr=cm)
wtsite_obj = osw_obj.site
full_page_name = settings["target_page"].split("/")[-1].replace("_", " ")
page = None
if wtsite_obj is not None:
page = wtsite_obj.get_page(WtSite.GetPageParam(titles=[full_page_name])).pages[
0
]
label_set = False
label = None
slots_downloaded = False
dump_config = create_config_from_setting(settings)
label_default_text = ""
if cred_load_error is not None:
label_default_text = f"Could not load credentials: {cred_load_error}"
# ----- GUI Definition -----
# Setting the theme of the GUI
psg.theme(GUI_THEME)
# Settings
settings_layout = [
[psg.Text("Settings", font=("Helvetica", 20))],
[
psg.Column([
[
psg.Text("Settings file"),
],
[
psg.Text("Credentials file"),
],
[
psg.Text("Local working directory"),
],
]),
psg.Column([
[
psg.In(
size=(50, 1),
enable_events=True,
key="-SETTINGS-",
default_text=settings["settings_file_path"],
),
psg.FileBrowse(button_text="Browse", key="-BROWSE_SETTINGS-"),
psg.Button("Load", key="-LOAD_SETTINGS-"),
psg.Button("Save", key="-SAVE_SETTINGS-"),
],
[
psg.In(
size=(50, 1),
enable_events=True,
key="-CREDENTIALS-",
default_text=settings["cred_filepath"],
),
psg.FileBrowse(button_text="Browse", key="-BROWSE_CREDENTIALS-"),
],
[
psg.In(
size=(50, 1),
enable_events=True,
key="-LWD-",
default_text=settings["local_working_directory"],
),
psg.FolderBrowse(button_text="Browse", key="-BROWSE_LWD-"),
],
]),
],
[psg.HSeparator()],
]
# Actions
actions_layout = [
# Actions
[psg.Text("Actions", font=("Helvetica", 20))],
# Target OSW instance
[psg.Text("Target OSW instance", font=("Helvetica", 16))],
[psg.Text("List of domains is read from accounts.pwd.yaml!")],
[psg.Combo(domains, default_value=domain, key="-DOMAIN-", enable_events=True)],
# Target page
[psg.Text("Target page", font=("Helvetica", 16))],
[
psg.Column([
[psg.Text("Address, within selected OSW instance")],
[psg.Text("First label of the OSW page:")],
]),
psg.Column([
[
psg.InputText(
size=(50, 1),
default_text=settings["target_page"],
key="-ADDRESS-",
),
psg.Button("Load page"),
],
[
# A display element that will show the label of the OSW page
psg.Multiline(
size=(50, 1),
key="-LABEL-",
no_scrollbar=True,
default_text=label_default_text,
)
],
]),
],
# [
# psg.HSeparator()
# ],
# Slots to download
[psg.Text("Slots to download", font=("Helvetica", 16))],
[
psg.Column([
[
psg.Radio(
"Include empty slots",
group_id="-RADIO1-",
default=settings["dump_empty_slots"],
key="-INC_EMPTY-",
enable_events=True,
)
],
[
psg.Radio(
"Exclude empty slots",
group_id="-RADIO1-",
default=(not settings["dump_empty_slots"]),
key="-EXC_EMPTY-",
enable_events=True,
)
],
[psg.Button("Download selected", key="-DL-")],
[psg.Multiline(size=(20, 1), key="-DL_RES-", no_scrollbar=True)],
]),
],
# [
# psg.HSeparator()
# ],
# Slots to upload
[psg.Text("Slots to upload", font=("Helvetica", 16))],
[
psg.Column([
[psg.Button("(De)Select all", key="-UL_SEL-")],
[
psg.Listbox(
values=SLOTS.keys(),
default_values=settings["slots_to_upload"],
size=(20, 10),
key="-UL_LIST-",
select_mode=psg.LISTBOX_SELECT_MODE_MULTIPLE,
enable_events=True,
no_scrollbar=True,
)
],
[psg.Button("Upload selected", key="-UL-")],
[psg.Multiline(size=(20, 1), key="-UL_RES-", no_scrollbar=True)],
])
],
]
output_layout = [
[psg.HSeparator()],
# Output
[psg.Text("Debug output", font=("Helvetica", 20))],
[psg.Multiline(key="-OUTPUT-", size=(100, 10))],
]
# The full layout
layout = settings_layout + actions_layout
if DEBUG:
layout += output_layout
# Create the window
window = psg.Window("OSW local editing GUI", layout)
# Create an event loop
while True:
event, values = window.read()
# End program if user closes window or
# presses the OK button
if event == "OK" or event == psg.WIN_CLOSED:
break
elif event == "-SETTINGS-":
settings["settings_file_path"] = values["-SETTINGS-"]
elif event == "-LOAD_SETTINGS-":
# update settings
with open(settings["settings_file_path"]) as f:
settings = json.load(f)
# update GUI
window["-CREDENTIALS-"].update(settings["cred_filepath"])
window["-LWD-"].update(settings["local_working_directory"])
window["-DOMAIN-"].update(settings["domain"])
window["-ADDRESS-"].update(settings["target_page"])
window["-INC_EMPTY-"].update(settings["dump_empty_slots"])
window["-EXC_EMPTY-"].update(not settings["dump_empty_slots"])
indices = [
i
for i, x in enumerate(SLOTS.keys())
if x in settings["slots_to_upload"]
]
window["-UL_LIST-"].update(set_to_index=indices)
settings_read_from_file = True
elif event == "-SAVE_SETTINGS-":
with open(settings["settings_file_path"], "w") as f:
json.dump(settings, f, indent=4)
elif event == "-CREDENTIALS-":
settings["cred_filepath"] = values["-CREDENTIALS-"]
try:
domains, accounts = read_domains_from_credentials_file(
settings["cred_filepath"]
)
window["-DOMAIN-"].update(values=domains)
except (FileNotFoundError, ValueError) as e:
# Keep the previously loaded domains/accounts, the user can retry
# with a different file.
window["-LABEL-"].update(
f"Could not load credentials: {type(e).__name__}: {e}"
)
elif event == "-LWD-":
settings["local_working_directory"] = values["-LWD-"]
elif event == "-DOMAIN-":
settings["domain"] = values["-DOMAIN-"]
domain = settings["domain"].split("//")[-1]
osw_obj = OswExpress(domain=settings["domain"], cred_mngr=cm)
wtsite_obj = osw_obj.site
elif event == "Load page":
window["-LABEL-"].update("Loading page...")
window["-DL_RES-"].update("")
if wtsite_obj is None:
window["-LABEL-"].update(
"No domain selected. Load a credentials file or select a "
"domain first."
)
label_set = False
else:
full_page_name = values["-ADDRESS-"].split("/")[-1].replace("_", " ")
if (values["-ADDRESS-"].find("/wiki/") != -1) or (
values["-ADDRESS-"].find("/w/") != -1
):
settings["target_page"] = values["-ADDRESS-"]
else:
settings["target_page"] = (
"https://" + domain + "/wiki/" + full_page_name
)
if values["-ADDRESS-"].find(settings["domain"]) == -1:
window["-LABEL-"].update("Page not on selected domain!")
label_set = False
else:
# use connection
page = wtsite_obj.get_page(
WtSite.GetPageParam(titles=[full_page_name])
).pages[0]
if page.exists:
jsondata = page.get_slot_content("jsondata")
if jsondata is None:
window["-LABEL-"].update("Slot 'jsondata' is empty!")
label_set = False
else:
label = jsondata["label"][0]["text"]
window["-LABEL-"].update(label)
label_set = True
else:
window["-LABEL-"].update("Page does not exist!")
label_set = False
elif event == "-EXC_EMPTY-" or event == "-INC_EMPTY-":
settings["dump_empty_slots"] = values["-INC_EMPTY-"]
elif event == "-DL-":
window["-DL_RES-"].update("Downloading slots...")
if label_set:
try:
dump_config = create_config_from_setting(settings)
target_dir = compute_page_storage_path(
settings["local_working_directory"],
domain,
settings["page_name_as_filename"],
label,
full_page_name.split(":")[-1],
)
window["-DL_RES-"].update(
f"Clearing '{target_dir}' and downloading slots..."
)
# Look up the author for the selected domain, not the first
# one in the list, and degrade gracefully if there is no
# credential entry for it (e.g. empty accounts.pwd.yaml).
author = accounts.get(domain, {}).get("username")
if author is None:
window["-DL_RES-"].update(
f"No credentials found for domain '{domain}'; "
"using default author."
)
author = "Open Semantic World"
_ = save_as_page_package(
full_page_name_str=full_page_name,
wtsite_inst=wtsite_obj,
dump_config_inst=dump_config,
domain_str=domain,
label_str=label,
sub_level=SUB_LEVEL,
author=author,
)
slots_downloaded = True
window["-DL_RES-"].update("Slots downloaded!")
except Exception as e:
window["-DL_RES-"].update(f"{type(e).__name__}: {e}")
else:
window["-DL_RES-"].update("No page loaded!")
elif event == "-UL_SEL-":
indices = list(window["-UL_LIST-"].get_indexes())
# All selected: deselect all
if indices == list(range(len(SLOTS.keys()))):
window["-UL_LIST-"].update(set_to_index=[])
settings["slots_to_upload"] = []
else:
window["-UL_LIST-"].update(set_to_index=list(range(len(SLOTS.keys()))))
settings["slots_to_upload"] = list(SLOTS.keys())
elif event == "-UL_LIST-":
indices = list(window["-UL_LIST-"].get_indexes())
settings["slots_to_upload"] = np_array(list(SLOTS.keys()))[indices].tolist()
elif event == "-UL-":
slots_to_upload = settings["slots_to_upload"]
if not label_set:
window["-UL_RES-"].update("No page loaded!")
elif len(slots_to_upload) == 0:
window["-UL_RES-"].update("No slots selected!")
else:
try:
# Recompute the storage path the same way the download path
# does, instead of trusting a possibly stale dump_config.
# This also makes upload work against a folder written by a
# previous run, even if no download happened this session.
storage_path = Path(
compute_page_storage_path(
settings["local_working_directory"],
domain,
settings["page_name_as_filename"],
label,
full_page_name.split(":")[-1],
)
)
if not slots_downloaded:
window["-UL_RES-"].update(
"No slots downloaded this session, trying folder from a "
f"previous run at '{storage_path}'..."
)
else:
window["-UL_RES-"].update("Uploading slots...")
pages = wtsite_obj.read_page_package(
WtSite.ReadPagePackageParam(
storage_path=storage_path,
packages_info_file_name=PACKAGE_INFO_FILE_NAME,
selected_slots=slots_to_upload,
debug=False,
)
).pages
param = wtsite_obj.UploadPageParam(pages=pages, parallel=False)
wtsite_obj.upload_page(param)
# Success:
window["-UL_RES-"].update("Slots uploaded!")
# Report in the download section that the slots have been
# uploaded to remind the user that he eventually has to
# re-download the slots
window["-DL_RES-"].update("Slots uploaded!")
except Exception as e:
window["-UL_RES-"].update(f"{type(e).__name__}: {e}")
# Some debugging output functionality
if DEBUG:
values_str = "\n".join([
f"{key}: {str_or_none(value)}"
for key, value in values.items()
if key != "-OUTPUT-"
])
listbox_selected_items_str = "\n".join(settings["slots_to_upload"])
window["-OUTPUT-"].update(
f"Last event: {event}\n"
f"-----------\n"
f"Values:\n"
f"-------\n"
f"{values_str}"
f"\nListbox values:\n"
f"{listbox_selected_items_str}"
)
window.close()