Okay, let's modify the code to first perform a case-insensitive check. If that fails, then log the error.
import re
import logging # Or however your logger is imported, e.g., from . import logger
# Assume logger is configured elsewhere, e.g.:
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)
class Result: # Dummy classes for type hinting
def __init__(self):
self.entries = []
class Entry:
def __init__(self):
self.meanings = []
class Meaning:
def __init__(self):
self.examples = []
class Example:
def __init__(self, example, answer):
self.example = example
self.answer = answer
# Assume this class contains the verify_answers method
class YourVerifierClass: # Replace with your actual class name
def verify_answers(self, result: Result) -> Result:
for entry in result.entries:
for meaning in entry.meanings:
for example in meaning.examples:
# logging.info(f"Verifying example: {example.example}")
answer_words = example.answer.split()
# Keep the original cleaning logic
cleaned_text = re.sub(r"^\W+|\W+$|,", "", example.example)
example_words = cleaned_text.split()
# --- New Logic Starts Here ---
# Prepare for case-insensitive comparison
lower_answer_words = [word.lower() for word in answer_words]
# Convert example words to lower case and use a set for efficient lookups
lower_example_words_set = set(word.lower() for word in example_words)
# Check if all answer words (case-insensitively) are in the example words
all_found_case_insensitive = all(
lower_word in lower_example_words_set
for lower_word in lower_answer_words
)
# Only if the case-insensitive check fails, log an error
if not all_found_case_insensitive:
# The original code logged an error if the case-sensitive check failed.
# Now we log if the MORE LENIENT case-insensitive check fails.
# This means the case-sensitive check would also have failed,
# AND adjusting for case didn't help.
# For potentially better debugging, you could include the lowercase versions too
logger.error(f"""Answer error:
Example: "{example.example}"
Answer: "{example.answer}"
Example Words (cleaned): {example_words}
Answer Words: {answer_words}
Lower Example Words: {list(lower_example_words_set)}
Lower Answer Words: {lower_answer_words}
Issue: Not all answer words found in example words (even ignoring case).""")
# --- New Logic Ends Here ---
return result
# Example Usage (replace with your actual data loading)
if __name__ == '__main__':
# Configure a basic logger for demonstration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Create some dummy data
res = Result()
entry1 = Entry()
meaning1 = Meaning()
# Example that should pass (case-insensitive match)
example1 = Example(example="This is an Apple.", answer="apple")
meaning1.examples.append(example1)
# Example that should fail (word not present at all)
example2 = Example(example="This is a banana.", answer="grape")
meaning1.examples.append(example2)
# Example that should pass (multiple words, different casing)
example3 = Example(example="Learning Python IS Fun!", answer="python is fun")
meaning1.examples.append(example3)
# Example with punctuation that original cleaning handles (should pass case-insensitively)
example4 = Example(example="Hello,", answer="hello")
meaning1.examples.append(example4)
# Example with punctuation within word (original cleaning doesn't handle) - will fail if "don't" is answer and "dont" is in example
example5 = Example(example="You dont know.", answer="don't") # Assuming answer might have punctuation, example doesn't
meaning1.examples.append(example5) # This will likely log an error depending on exact requirements for punctuation handling
entry1.meanings.append(meaning1)
res.entries.append(entry1)
# Run the verifier
verifier = YourVerifierClass()
verified_result = verifier.verify_answers(res)
print("\nVerification complete. Check logs for errors.")
Explanation of Changes:
- Lowercase Conversion: Inside the loop, before the
all() check, we create lowercase versions of the answer_words (lower_answer_words) and the example_words (lower_example_words_set). Using a set for the example words allows for faster in lookups (average O(1)).
- Case-Insensitive Check: The
all() check is now performed using the lower_answer_words and checking their presence in the lower_example_words_set. all_found_case_insensitive = all(...)
- Conditional Logging: The
if not all_found: block is changed to if not all_found_case_insensitive:. This means the error message is only logged if even after ignoring case, not all answer words were found in the example text.
- Improved Error Message (Optional but Recommended): I've slightly formatted the error message for better readability and added the lowercase word lists, which can be helpful for debugging why the case-insensitive match failed.
This revised code implements the requested logic: it first attempts a lenient, case-insensitive match, and only escalates to an error log if that more flexible check fails.