|
| 1 | +import csv |
| 2 | +from pathlib import Path |
| 3 | +from src.utils.logging_config import setup_logger |
| 4 | +from typing import Optional |
| 5 | + |
| 6 | +logger = setup_logger(__name__) |
| 7 | + |
| 8 | + |
| 9 | +class CachedItemEntry: |
| 10 | + def __init__(self, content: str, is_pineapple: bool): |
| 11 | + self.content = content |
| 12 | + self.is_pineapple = is_pineapple |
| 13 | + |
| 14 | + |
| 15 | +class CSVItemCacher: |
| 16 | + def __init__(self, csv_file: Path, delimiter: str = ","): |
| 17 | + self.csv_file = csv_file |
| 18 | + self.delimiter = delimiter |
| 19 | + self.data = self._load_data() |
| 20 | + |
| 21 | + def _load_data(self): |
| 22 | + """Loads data from the CSV file into a list.""" |
| 23 | + data = [] |
| 24 | + try: |
| 25 | + with open(self.csv_file, "r", newline="") as file: |
| 26 | + reader = csv.DictReader(file, delimiter=self.delimiter) |
| 27 | + for row in reader: |
| 28 | + content = row["content"] |
| 29 | + is_pineapple = row["is_pineapple"].lower() == "true" |
| 30 | + |
| 31 | + data.append(CachedItemEntry(content, is_pineapple)) |
| 32 | + except FileNotFoundError: |
| 33 | + logger.info(f"File not found: {self.csv_file}. Creating new one.") |
| 34 | + data = [] |
| 35 | + except KeyError as e: |
| 36 | + logger.error(f"csv file is missing required column {e}") |
| 37 | + data = [] |
| 38 | + except Exception as e: |
| 39 | + logger.error(f"Error loading data from csv: {e}") |
| 40 | + data = [] |
| 41 | + return data |
| 42 | + |
| 43 | + def get(self, content: str) -> Optional[CachedItemEntry]: |
| 44 | + """Retrieves the is_pineapple value for the given content.""" |
| 45 | + for entry in self.data: |
| 46 | + if entry.content == content: |
| 47 | + return entry |
| 48 | + return None |
| 49 | + |
| 50 | + def set(self, content: str, is_pineapple: bool): |
| 51 | + """Sets the is_pineapple value for the given content and writes to CSV.""" |
| 52 | + for entry in self.data: |
| 53 | + if entry.content == content: |
| 54 | + entry.is_pineapple = is_pineapple |
| 55 | + self._save_data() |
| 56 | + return |
| 57 | + self.data.append(CachedItemEntry(content, is_pineapple)) |
| 58 | + self._save_data() |
| 59 | + |
| 60 | + def _save_data(self): |
| 61 | + """Saves the data to the CSV file.""" |
| 62 | + try: |
| 63 | + with open(self.csv_file, "w", newline="") as file: |
| 64 | + writer = csv.DictWriter( |
| 65 | + file, |
| 66 | + fieldnames=["content", "is_pineapple"], |
| 67 | + delimiter=self.delimiter, |
| 68 | + ) |
| 69 | + writer.writeheader() |
| 70 | + for entry in self.data: |
| 71 | + writer.writerow( |
| 72 | + {"content": entry.content, "is_pineapple": entry.is_pineapple} |
| 73 | + ) |
| 74 | + except Exception as e: |
| 75 | + logger.error(f"Error saving data to CSV: {e}") |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + # Example usage: |
| 80 | + cacher = CSVItemCacher(Path("my_data.csv")) |
| 81 | + |
| 82 | + # Get a value |
| 83 | + is_pineapple = cacher.get("apple") |
| 84 | + print(f"Is 'apple' pineapple? {is_pineapple}") |
| 85 | + |
| 86 | + # Set a value |
| 87 | + cacher.set("banana", True) |
| 88 | + print("Set 'banana' to pineapple.") |
| 89 | + |
| 90 | + # Get the updated value |
| 91 | + is_pineapple = cacher.get("banana") |
| 92 | + print(f"Is 'banana' pineapple? {is_pineapple}") |
0 commit comments