|
| 1 | +import json |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +STATS_FILE = Path.home() / ".postalregex_stats.json" |
| 5 | + |
| 6 | +def _load_stats(): |
| 7 | + """Load statistics from the local JSON file.""" |
| 8 | + if not STATS_FILE.exists(): |
| 9 | + return {} |
| 10 | + with open(STATS_FILE, "r") as f: |
| 11 | + try: |
| 12 | + return json.load(f) |
| 13 | + except json.JSONDecodeError: |
| 14 | + return {} |
| 15 | + |
| 16 | +def _save_stats(stats): |
| 17 | + """Save statistics to the local JSON file.""" |
| 18 | + with open(STATS_FILE, "w") as f: |
| 19 | + json.dump(stats, f, indent=2) |
| 20 | + |
| 21 | +def record_validation(country_code, is_valid): |
| 22 | + """ |
| 23 | + Record a validation attempt for a given country. |
| 24 | +
|
| 25 | + Args: |
| 26 | + country_code (str): The ISO 3166-1 alpha-2 country code. |
| 27 | + is_valid (bool): True if the validation was successful, False otherwise. |
| 28 | + """ |
| 29 | + stats = _load_stats() |
| 30 | + |
| 31 | + # Ensure the country entry exists |
| 32 | + if country_code not in stats: |
| 33 | + stats[country_code] = {"valid": 0, "invalid": 0} |
| 34 | + |
| 35 | + # Increment the appropriate counter |
| 36 | + if is_valid: |
| 37 | + stats[country_code]["valid"] += 1 |
| 38 | + else: |
| 39 | + stats[country_code]["invalid"] += 1 |
| 40 | + _save_stats(stats) |
| 41 | + |
| 42 | +def reset_stats(): |
| 43 | + """Clear all recorded statistics.""" |
| 44 | + if STATS_FILE.exists(): |
| 45 | + STATS_FILE.unlink() |
| 46 | + print("Local validation statistics have been reset.") |
| 47 | + else: |
| 48 | + print("No statistics file found to reset.") |
| 49 | + |
| 50 | +def get_stats() -> dict: |
| 51 | + """ |
| 52 | + Loads and returns the validation statistics from the stats file. |
| 53 | + This function only retrieves data and does not print anything. |
| 54 | + |
| 55 | + Returns: |
| 56 | + dict: A dictionary containing the validation stats, or an empty dict if none exist. |
| 57 | + """ |
| 58 | + if not STATS_FILE.exists(): |
| 59 | + return {} |
| 60 | + try: |
| 61 | + with open(STATS_FILE, "r") as f: |
| 62 | + return json.load(f) |
| 63 | + except (json.JSONDecodeError, FileNotFoundError): |
| 64 | + return {} |
| 65 | + |
| 66 | +def show_stats(): |
| 67 | + """ |
| 68 | + Loads and prints a formatted dashboard of the validation statistics. |
| 69 | + This function handles all presentation logic. |
| 70 | + """ |
| 71 | + stats = get_stats() # This is the main change: call the new data function |
| 72 | + if not stats: |
| 73 | + print("No validation statistics recorded yet.") |
| 74 | + return |
| 75 | + |
| 76 | + # Prepare data for the table |
| 77 | + table_data = [] |
| 78 | + for country, counts in stats.items(): |
| 79 | + valid = counts.get("valid", 0) |
| 80 | + invalid = counts.get("invalid", 0) |
| 81 | + total = valid + invalid |
| 82 | + table_data.append([country, valid, invalid, total]) |
| 83 | + |
| 84 | + # Sort by total validations |
| 85 | + table_data.sort(key=lambda row: row[3], reverse=True) |
| 86 | + |
| 87 | + # --- Print Table --- |
| 88 | + print("\nPostal Code Validation Stats (Local Project)") |
| 89 | + header = ["Country", "Valid", "Invalid", "Total"] |
| 90 | + col_widths = [len(h) for h in header] |
| 91 | + for row in table_data: |
| 92 | + for i, cell in enumerate(row): |
| 93 | + col_widths[i] = max(col_widths[i], len(str(cell))) |
| 94 | + |
| 95 | + header_line = " | ".join(h.ljust(w) for h, w in zip(header, col_widths)) |
| 96 | + separator = "-+-".join("-" * w for w in col_widths) |
| 97 | + print(header_line) |
| 98 | + print(separator) |
| 99 | + |
| 100 | + for row in table_data: |
| 101 | + row_line = " | ".join(str(cell).ljust(w) for cell, w in zip(row, col_widths)) |
| 102 | + print(row_line) |
| 103 | + |
| 104 | + # --- Print Bar Chart --- |
| 105 | + print("\nValidation Success Rate") |
| 106 | + for country, valid, invalid, total in table_data: |
| 107 | + if total == 0: |
| 108 | + success_rate = 0 |
| 109 | + else: |
| 110 | + success_rate = (valid / total) * 100 |
| 111 | + bar_length = 40 |
| 112 | + filled_length = int(bar_length * success_rate / 100) |
| 113 | + bar = "█" * filled_length + " " * (bar_length - filled_length) |
| 114 | + print(f"{country.ljust(5)} |{bar}| {success_rate:.0f}% valid") |
0 commit comments