Skip to content

Commit 1aa2cfa

Browse files
committed
Refactor: Use % style string formatting for logging.
1 parent 05ac543 commit 1aa2cfa

8 files changed

Lines changed: 46 additions & 37 deletions

File tree

ingredient_parser/en/_structure_features.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ def detect_mip_phrases(self, tokenized_sentence: list[Token]) -> list[list[int]]
195195

196196
text_pos = [(token.text, token.pos_tag) for token in self.tokenized_sentence]
197197
parsed = self.mip_parser.parse(text_pos)
198-
logger.debug(f"MIP parser: \n{parsed}")
198+
logger.debug("MIP parser: \n%s", parsed)
199199
for indices in self._get_subtree_indices(parsed, ["EMIP", "MIP"]): # type: ignore
200200
# If the conjunction is not "or", skip
201201
if self._cc_is_not_or(text_pos, indices):
@@ -249,7 +249,7 @@ def detect_sentences_splits(self, tokenized_sentence: list[Token]) -> list[int]:
249249
text_pos.append((t.feat_text, pos))
250250

251251
parsed = self.compound_parser.parse(text_pos)
252-
logger.debug(f"Sentence split parser: \n{parsed}")
252+
logger.debug("Sentence split parser: \n%s", parsed)
253253
for indices in self._get_subtree_indices(parsed, ["CS_WU", "CS_NU", "CS_HALF"]): # type: ignore
254254
# If the conjunction is not "or", skip
255255
if self._cc_is_not_or(text_pos, indices):
@@ -281,7 +281,7 @@ def detect_examples(self, tokenized_sentence: list[Token]) -> list[list[int]]:
281281

282282
text_pos = [(token.text, token.pos_tag) for token in self.tokenized_sentence]
283283
parsed = self.example_parser.parse(text_pos)
284-
logger.debug(f"Example parser: \n{parsed}")
284+
logger.debug("Example parser: \n%s", parsed)
285285
for indices in self._get_subtree_indices(parsed, ["EX"]): # type: ignore
286286
phrase_text_pos = [
287287
(token.text.upper(), token.pos_tag)
@@ -347,7 +347,7 @@ def detect_dimensional_phrases(
347347
text_pos.append((t.feat_text, pos))
348348

349349
parsed = self.dimensional_phrase_parser.parse(text_pos)
350-
logger.debug(f"Dimensional phrase parser: \n{parsed}")
350+
logger.debug("Dimensional phrase parser: \n%s", parsed)
351351
dimensional_phrases = self._get_subtree_indices(parsed, ["DP"]) # type: ignore
352352
return dimensional_phrases
353353

ingredient_parser/en/foundationfoods/_ff_utils.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ def normalise_spelling(tokens: list[IngredientToken]) -> list[IngredientToken]:
163163

164164
if normalised_tokens != tokens:
165165
norm_tokens = [t.token for t in normalised_tokens]
166-
logger.debug(f"Normalised '{[t.token for t in tokens]}' to '{norm_tokens}'.")
166+
logger.debug("Normalised '%s' to '%s'.", [t.token for t in tokens], norm_tokens)
167167

168168
return normalised_tokens
169169

@@ -230,7 +230,8 @@ def load_fdc_ingredients() -> list[FDCIngredient]:
230230
tokenized_description = tokenize_fdc_description(row["description"])
231231
if not tokenized_description.embedding_tokens:
232232
logger.debug(
233-
f"'{row['description']}' has no tokens in embedding vocabulary."
233+
"'%s' has no tokens in embedding vocabulary.",
234+
row["description"],
234235
)
235236
continue
236237
foundation_foods.append(
@@ -247,7 +248,7 @@ def load_fdc_ingredients() -> list[FDCIngredient]:
247248
)
248249
)
249250

250-
logger.debug(f"Loaded {len(foundation_foods)} FDC ingredients.")
251+
logger.debug("Loaded %d FDC ingredients.", len(foundation_foods))
251252
return foundation_foods
252253

253254

ingredient_parser/en/foundationfoods/_foundationfoods.py

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -94,13 +94,13 @@ def match_foundation_foods(
9494
name_tokens = [IngredientToken(token, tag) for token, tag in zip(tokens, pos_tags)]
9595

9696
name_tokens = strip_ambiguous_leading_adjectives(name_tokens)
97-
logger.debug(f"Matching FDC ingredient for ingredient name tokens: {tokens}")
97+
logger.debug("Matching FDC ingredient for ingredient name tokens: %s", tokens)
9898
prepared_tokens = prepare_tokens(tuple(name_tokens))
9999
if not prepared_tokens:
100100
logger.debug("Ingredient name has no tokens valid for matching.")
101101
return None
102102
else:
103-
logger.debug(f"Prepared tokens: {prepared_tokens}.")
103+
logger.debug("Prepared tokens: %s.", prepared_tokens)
104104

105105
normalised_tokens = normalise_spelling(prepared_tokens)
106106

@@ -158,7 +158,9 @@ def match_foundation_foods(
158158
# Check if both BM25 and uSIF agree on the top result. If they do, return that and
159159
# avoid any further processing.
160160
if fdc := consistent_top_result(bm25_matches, usif_matches):
161-
logger.debug(f"BM25 and uSIF rankers agree on best match: {fdc.fdc_id=}")
161+
logger.debug(
162+
"BM25 and uSIF rankers agree on best match: fdc.fdc_id=%s", fdc.fdc_id
163+
)
162164
return FoundationFood(
163165
text=fdc.description,
164166
confidence=1.0,
@@ -177,12 +179,14 @@ def match_foundation_foods(
177179
m.fdc.fdc_id for m in bm25_matches[:TOP_K]
178180
}
179181
logger.debug(
180-
f"BM25 and uSIF ranker alignment is below threshold "
181-
f"({bm25_usif_agreement=:.4f} < {BM25_USIF_AGREENMENT_THRESHOLD=})."
182+
"BM25 and uSIF ranker alignment is below threshold "
183+
"(bm25_usif_agreement=%.4f < BM25_USIF_AGREENMENT_THRESHOLD=%f).",
184+
bm25_usif_agreement,
185+
BM25_USIF_AGREENMENT_THRESHOLD,
182186
)
183187
logger.debug(
184-
f"Using FuzzyMatcher on top {TOP_K} matches from "
185-
"BM25 and uSIF to help arbitrate."
188+
"Using FuzzyMatcher on top %d matches from BM25 and uSIF to arbitrate.",
189+
TOP_K,
186190
)
187191

188192
fuzzy = get_fuzzy_ranker()
@@ -213,16 +217,17 @@ def match_foundation_foods(
213217
)
214218
if matches_with_top_score > len(DATASET_PREFERENCE):
215219
logger.debug(
216-
f"Top score shared by {matches_with_top_score} FDC entries "
217-
"therefore cannot determine suitable match."
220+
"Top score shared by %d FDC entries therefore cannot determine match.",
221+
matches_with_top_score,
218222
)
219223
return None
220224

221225
match_quality = determine_match_quality(best_match, usif_matches, fuzzy_matches)
222226
if match_quality.quality == "poor":
223227
logger.debug(
224-
f"Rejected best match of '{best_match.fdc.description}' because "
225-
f"{match_quality.reason}."
228+
"Rejected best match of '%s' because %s.",
229+
best_match.fdc.description,
230+
match_quality.reason,
226231
)
227232
return None
228233

@@ -552,10 +557,10 @@ def fuse_results(
552557
fuzzy_conf = fuzzy_conf / total_conf * 3
553558
usif_conf = usif_conf / total_conf * 3
554559
logger.debug(
555-
f"Ranker confidences: "
556-
f"BM25={bm25_conf:.4f}, "
557-
f"uSIF={usif_conf:.4f}, "
558-
f"Fuzzy={fuzzy_conf:.4f}."
560+
"Ranker confidences: BM25=%.4f, uSIF=%.4f, Fuzzy=%.4f.",
561+
bm25_conf,
562+
usif_conf,
563+
fuzzy_conf,
559564
)
560565

561566
fused_matches = []

ingredient_parser/en/parser.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def parse_ingredient_en(
6767
ParsedIngredient
6868
ParsedIngredient object of structured data parsed from input string.
6969
"""
70-
logger.debug(f'Parsing sentence "{sentence}" using "en" parser.')
70+
logger.debug("Parsing sentence '%s' using 'en' parser.", sentence)
7171
TAGGER = load_parser_model()
7272

7373
if custom_units is None:
@@ -84,7 +84,7 @@ def parse_ingredient_en(
8484
labels, scores = zip(*TAGGER.tag_from_features(features, expect_name_in_output))
8585
labels = list(labels)
8686
scores = list(scores)
87-
logger.debug(f"Sentence token labels: {labels}.")
87+
logger.debug("Sentence token labels: %s.", labels)
8888

8989
labelled_tokens = [
9090
LabelledToken(
@@ -173,7 +173,7 @@ def inspect_parser_en(
173173
ParserDebugInfo object containing the PreProcessor object, PostProcessor
174174
object and Tagger.
175175
"""
176-
logger.debug(f'Parsing sentence "{sentence}" using "en" parser.')
176+
logger.debug("Parsing sentence '%s' using 'en' parser.", sentence)
177177
TAGGER = load_parser_model()
178178

179179
if custom_units is None:
@@ -190,7 +190,7 @@ def inspect_parser_en(
190190
labels, scores = zip(*TAGGER.tag_from_features(features, expect_name_in_output))
191191
labels = list(labels)
192192
scores = list(scores)
193-
logger.debug(f"Sentence token labels: {labels}.")
193+
logger.debug("Sentence token labels: %s.", labels)
194194

195195
labelled_tokens = [
196196
LabelledToken(

ingredient_parser/en/postprocess.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,10 @@ def parsed(self) -> ParsedIngredient:
196196
self.labels = name_replaced_labels
197197
logger.debug(
198198
(
199-
f"Relabelled tokens to {name_replaced_labels} ",
199+
"Relabelled tokens to %s ",
200200
"because seperate_name=False.",
201-
)
201+
),
202+
name_replaced_labels,
202203
)
203204

204205
# Process NAME labels as any other label, but return as a list
@@ -1073,7 +1074,9 @@ def _sizeable_unit_pattern(
10731074
amounts.append(first)
10741075
_ = match.pop(-1)
10751076

1076-
logger.debug(f"Implicit quantity of '1' applied to '1 {unit}'.")
1077+
logger.debug(
1078+
"Implicit quantity of '1' applied to '1 %s'.", unit
1079+
)
10771080
else:
10781081
# The first amount is made up of the first and last items
10791082
# Note that this cannot be singular, but may be approximate
@@ -1581,7 +1584,7 @@ def _fallback_pattern(
15811584

15821585
if amount.implicit_quantity:
15831586
logger.debug(
1584-
f"Implicit quantity of '{amount.quantity}' applied to '{text}'."
1587+
"Implicit quantity of '%s' applied to '%s'.", amount.quantity, text
15851588
)
15861589

15871590
return processed_amounts

ingredient_parser/en/preprocess.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ def __init__(self, input_sentence: str, custom_units: dict[str, str] | None = No
127127
"""
128128
self.input: str = input_sentence
129129
self.sentence: str = self._normalise(input_sentence)
130-
logger.debug(f'Normalised sentence: "{self.sentence}".')
130+
logger.debug("Normalised sentence: '%s'.", self.sentence)
131131

132132
if custom_units is not None:
133133
self._units = UNITS | custom_units
@@ -196,7 +196,7 @@ def _normalise(self, sentence: str) -> str:
196196

197197
for func in funcs:
198198
sentence = func(sentence)
199-
logger.debug(f"{func.__name__}: {sentence}")
199+
logger.debug("%s: %s", func.__name__, sentence)
200200

201201
return sentence.strip()
202202

@@ -625,8 +625,8 @@ def _calculate_tokens(self, sentence: str) -> list[Token]:
625625
)
626626
)
627627

628-
logger.debug(f"Tokenized sentence: {[t.text for t in tokens]}.")
629-
logger.debug(f"Singularised tokens at indices: {self.singularised_indices}.")
628+
logger.debug("Tokenized sentence: %s.", [t.text for t in tokens])
629+
logger.debug("Singularised tokens at indices: %s.", self.singularised_indices)
630630

631631
return tokens
632632

ingredient_parser/inference.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def tag_from_features(
128128

129129
if expect_name_in_output and all("NAME" not in label for label in labels):
130130
# No tokens were assigned the NAME label, so guess if there's a name
131-
logger.debug(f"No tokens found where name is most probable label: {labels}")
131+
logger.debug("No tokens labelled as NAME by model: %s", labels)
132132
labels, scores = self._guess_ingredient_name(labels, scores)
133133

134134
self._detect_invalid_label_sequence(labels)
@@ -285,7 +285,7 @@ def _guess_ingredient_name(
285285
labels[token_index] = new_label
286286
scores[token_index] = new_score
287287

288-
logger.debug(f"Found alternative name at token indices: {indices}")
288+
logger.debug("Found alternative name at token indices: %s", indices)
289289
return labels, scores
290290

291291
def _detect_invalid_label_sequence(self, labels: list[str]) -> None:

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ exclude = [
7474
line-length = 88
7575

7676
[tool.ruff.lint]
77-
select = ["E", "F", "I", "PERF", "PT", "RUF"]
77+
select = ["E", "F", "I", "PERF", "PT", "RUF", "G"]
7878
ignore = [
7979
"E402", # To enable path to be modified in doc conf.py before import
8080
"RUF001", # Ambiguous unicode characters are handled explicitly in functions

0 commit comments

Comments
 (0)