Skip to content

Commit 4b4462a

Browse files
committed
Log improvements, lang selection
1 parent fa0f850 commit 4b4462a

3 files changed

Lines changed: 46 additions & 15 deletions

File tree

geonode/base/management/commands/thesaurus.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,12 @@ def add_arguments(self, parser):
4343
choices=ACTIONS,
4444
help="Actions to run upon data loading (default: create)",
4545
)
46+
load_group.add_argument(
47+
"--langs",
48+
dest="langs",
49+
action="append",
50+
help="Only import labels for the requested languages; can be repeated",
51+
)
4652

4753
dump_group = parser.add_argument_group('Params for "dump" subcommand')
4854
dump_group.add_argument("-o", "--out", nargs="?", help="Full path to the output file to be created")
@@ -101,6 +107,8 @@ def handle(self, *args, **options):
101107
input_file = options.get("file")
102108
action = options.get("action")
103109
identifier = options.get("identifier")
110+
lang = options.get("lang")
111+
langs = options.get("langs") or []
104112

105113
if not input_file:
106114
raise CommandError("'load' command requires the <file> parameter.")
@@ -109,7 +117,7 @@ def handle(self, *args, **options):
109117
action = ACTION_CREATE
110118
logger.info(f"Missing action param: setting actions as '{action}'")
111119

112-
load_thesaurus(input_file, identifier, action)
120+
load_thesaurus(input_file, identifier, action, lang=lang, langs=langs)
113121

114122
elif subcommand == COMMAND_AUTOLOAD:
115123
autoload_thesauri()

geonode/base/management/commands/thesaurus_subcommands/autoload.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,16 @@ def autoload_thesauri():
1717
loaded = 0
1818
for app_config in apps.get_app_configs():
1919
thesauri_dir = os.path.join(app_config.path, "thesauri")
20+
logger.debug(f"Looking for auto thesaurus in app '{app_config.name}' path: {thesauri_dir}")
2021
if not os.path.isdir(thesauri_dir):
2122
continue
2223
rdf_files = [f for f in os.listdir(thesauri_dir) if f.lower().endswith(".rdf")]
2324
for rdf_file in sorted(rdf_files):
2425
rdf_path = os.path.join(thesauri_dir, rdf_file)
2526
logger.info(f"Autoloading thesaurus from app '{app_config.name}': {rdf_path}")
2627
try:
27-
load_thesaurus(rdf_path, identifier=None, action=ACTION_UPDATE)
28+
load_thesaurus(rdf_path, identifier=None, action=ACTION_UPDATE, log_details=False)
2829
loaded += 1
2930
except Exception as e:
30-
logger.error(f"Failed to load thesaurus '{rdf_path}': {e}")
31+
logger.error(f"Failed to load thesaurus '{rdf_path}': {e}", exc_info=True)
3132
logger.info(f"Autoload complete: {loaded} thesaurus file(s) loaded.")

geonode/base/management/commands/thesaurus_subcommands/load.py

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,16 @@
4545
FAKE_BASE_URI = "http://automatically/added/uri/"
4646

4747

48-
def load_thesaurus(input_file, identifier: str, action: str = ACTION_CREATE):
48+
def load_thesaurus(input_file, identifier: str, action: str = ACTION_CREATE, default_lang: str = None, langs: List[str] = [], log_details=True):
4949
g = Graph()
5050

5151
# if the input_file is an UploadedFile object rather than a file path the Graph.parse()
5252
# method may not have enough info to correctly guess the type; in this case supply the
5353
# name, which should include the extension, to guess_format manually...
5454

55+
# explodes list of comma separated langs into single list of langs
56+
langs = [lang for item in langs for lang in item.split(",")]
57+
5558
filename = input_file.name if isinstance(input_file, UploadedFile) else input_file
5659
rdf_format = guess_format(filename)
5760
if not identifier:
@@ -65,7 +68,7 @@ def load_thesaurus(input_file, identifier: str, action: str = ACTION_CREATE):
6568
if scheme is None:
6669
raise CommandError("ConceptScheme not found in file")
6770

68-
default_lang = getattr(settings, "THESAURUS_DEFAULT_LANG", None)
71+
default_lang = default_lang or getattr(settings, "THESAURUS_DEFAULT_LANG", None) or getattr(settings, "LANGUAGE_CODE", 'en')
6972

7073
available_titles = [t
7174
for t in itertools.chain(g.objects(scheme, DC.title), g.objects(scheme, DCTERMS.title))
@@ -81,15 +84,22 @@ def load_thesaurus(input_file, identifier: str, action: str = ACTION_CREATE):
8184
Thesaurus,
8285
{"identifier": identifier},
8386
{"date": date_issued, "description": description, "title": thesaurus_title, "about": str(scheme)},
84-
{"card_min": 0, "card_max": 0, "facet": False}
87+
{"card_min": 0, "card_max": 0, "facet": False},
88+
log_details
8589
)
8690

8791
tl_cnt = tl_add = 0
8892
tk_cnt = tk_add = 0
8993
tkl_cnt = tkl_add = 0
94+
tkl_skp = 0
9095

9196
for lang in available_titles:
9297
if lang.language is not None:
98+
tl_cnt += 1
99+
if langs and lang.language not in langs:
100+
logger.debug(f"Skipping label for language '{lang.language}' not in requested langs {langs}")
101+
tkl_skp += 1
102+
continue
93103
thesaurus_label, c = _run_action(
94104
action,
95105
ThesaurusLabel,
@@ -99,8 +109,8 @@ def load_thesaurus(input_file, identifier: str, action: str = ACTION_CREATE):
99109
},
100110
{"label": lang.value},
101111
{},
112+
log_details
102113
)
103-
tl_cnt += 1
104114
tl_add += 1 if c else 0
105115

106116
for concept in g.subjects(RDF.type, SKOS.Concept):
@@ -115,7 +125,8 @@ def load_thesaurus(input_file, identifier: str, action: str = ACTION_CREATE):
115125
available_labels = [t for t in g.objects(concept, SKOS.prefLabel) if isinstance(t, Literal)]
116126
alt_label = value_for_language(available_labels, default_lang) or about
117127

118-
logger.info(f" - Parsed Concept -> about:'{about}' alt:'{alt_label}' pref:'{str(pref)}' ")
128+
if log_details:
129+
logger.info(f" - Parsed Concept -> about:'{about}' alt:'{alt_label}' pref:'{str(pref)}' ")
119130

120131
tk, c = _run_action(
121132
action,
@@ -126,14 +137,21 @@ def load_thesaurus(input_file, identifier: str, action: str = ACTION_CREATE):
126137
},
127138
{"alt_label": alt_label},
128139
{},
140+
log_details
129141
)
130142
tk_cnt += 1
131143
tk_add += 1 if c else 0
132144

133145
for _, pref_label in preferredLabel(g, concept):
146+
tkl_cnt += 1
134147
lang = pref_label.language
148+
if langs and lang not in langs:
149+
logger.debug(f"Skipping label for language '{lang}' not in requested langs {langs}")
150+
tkl_skp += 1
151+
continue
135152
label = str(pref_label)
136-
logger.info(f" - Label {lang}: {label}")
153+
if log_details:
154+
logger.info(f" - Label {lang}: {label}")
137155

138156
tkl, c = _run_action(
139157
action,
@@ -144,8 +162,8 @@ def load_thesaurus(input_file, identifier: str, action: str = ACTION_CREATE):
144162
},
145163
{"label": label},
146164
{},
165+
log_details
147166
)
148-
tkl_cnt += 1
149167
tkl_add += 1 if c else 0
150168

151169
logger.warning(f"Thesaurus added: {cr_t}")
@@ -154,15 +172,16 @@ def load_thesaurus(input_file, identifier: str, action: str = ACTION_CREATE):
154172
logger.warning(f"ThesaurusKeywordLabel added: {tkl_add:3}/{tkl_cnt:3}")
155173

156174

157-
def _run_action(action: str, model: type[models.Model], pk_dict, upd_dict, create_dict) -> tuple[models.Model, bool]:
175+
def _run_action(action: str, model: type[models.Model], pk_dict, upd_dict, create_dict, log_details) -> tuple[models.Model, bool]:
158176
def update_or_create(defaults=upd_dict, create_defaults=create_dict, **pk_dict):
159177
# this signature is available since django 5
160178
obj, created = model.objects.get_or_create(defaults=upd_dict | create_dict, **pk_dict)
161179

162180
if not created:
163181
rows = model.objects.filter(pk=obj.pk).update(**upd_dict)
164182
if rows != 1:
165-
logger.error(f"UPDATED {rows} rows for {model.__name__} -> {pk_dict}")
183+
if log_details:
184+
logger.error(f"UPDATED {rows} rows for {model.__name__} -> {pk_dict}")
166185

167186
return obj, created
168187

@@ -176,14 +195,17 @@ def update_or_create(defaults=upd_dict, create_defaults=create_dict, **pk_dict):
176195
elif action == ACTION_UPDATE:
177196
obj, created = update_or_create(defaults=upd_dict, create_defaults=create_dict, **pk_dict)
178197
if created:
179-
logger.info(f"{model.__name__} -> Created id:{pk_dict}")
198+
if log_details:
199+
logger.info(f"{model.__name__} -> Created id:{pk_dict}")
180200
else:
181-
logger.info(f"{model.__name__} -> Updated id:{pk_dict} DATA:{upd_dict}")
201+
if log_details:
202+
logger.info(f"{model.__name__} -> Updated id:{pk_dict} DATA:{upd_dict}")
182203

183204
elif action == ACTION_APPEND:
184205
obj, created = model.objects.get_or_create(defaults=upd_dict | create_dict, **pk_dict)
185206
if created:
186-
logger.info(f"{model.__name__} -> Created {pk_dict}")
207+
if log_details:
208+
logger.info(f"{model.__name__} -> Created {pk_dict}")
187209
else:
188210
raise CommandError("No valid action found")
189211

0 commit comments

Comments
 (0)