""" History Manager for Handwritten Marathi Extraction App. Persists test extraction runs, structured JSON results, raw Devanagari transcriptions, and associated document images across server restarts. """ import os import io import csv import json import uuid import shutil import logging import threading from datetime import datetime logger = logging.getLogger(__name__) BASE_DIR = os.path.abspath(os.path.dirname(__file__)) DATA_DIR = os.path.join(BASE_DIR, "data") IMAGES_DIR = os.path.join(DATA_DIR, "images") HISTORY_FILE = os.path.join(DATA_DIR, "test_history.json") class HistoryManager: """Thread-safe manager for persisting and querying document extraction history.""" _lock = threading.Lock() @classmethod def _ensure_dirs(cls): """Ensure storage directories exist.""" os.makedirs(DATA_DIR, exist_ok=True) os.makedirs(IMAGES_DIR, exist_ok=True) @classmethod def load_all(cls) -> list: """Load all history records from disk.""" cls._ensure_dirs() if not os.path.exists(HISTORY_FILE): return [] try: with open(HISTORY_FILE, "r", encoding="utf-8") as f: data = json.load(f) return data if isinstance(data, list) else [] except Exception as e: logger.error(f"Failed to load history from {HISTORY_FILE}: {e}") return [] @classmethod def save_all(cls, records: list) -> bool: """Save history records to disk atomically.""" cls._ensure_dirs() temp_file = f"{HISTORY_FILE}.tmp" try: with open(temp_file, "w", encoding="utf-8") as f: json.dump(records, f, ensure_ascii=False, indent=2) # Atomic rename on Windows/Unix os.replace(temp_file, HISTORY_FILE) return True except Exception as e: logger.error(f"Failed to save history to {HISTORY_FILE}: {e}") if os.path.exists(temp_file): try: os.remove(temp_file) except OSError: pass return False @classmethod def add_entry( cls, entry: dict, original_bytes: bytes = None, processed_bytes: bytes = None, file_ext: str = "jpg" ) -> dict: """ Add a new test result entry and optionally save document images. Args: entry: Dict containing test metadata and extraction results. original_bytes: Raw bytes of the uploaded image. processed_bytes: Raw bytes of the preprocessed image. file_ext: Extension of the image (default: jpg). Returns: The saved entry dict. """ cls._ensure_dirs() with cls._lock: records = cls.load_all() entry_id = entry.get("id") or str(uuid.uuid4())[:8] entry["id"] = entry_id if "timestamp" not in entry: entry["timestamp"] = datetime.now().isoformat() # Clean extension ext = file_ext.lstrip(".").lower() if ext not in ("jpg", "jpeg", "png", "bmp", "tiff", "pdf"): ext = "jpg" # Save original image if provided entry["has_original_image"] = False if original_bytes: orig_filename = f"{entry_id}_orig.{ext}" orig_path = os.path.join(IMAGES_DIR, orig_filename) try: with open(orig_path, "wb") as f: f.write(original_bytes) entry["has_original_image"] = True entry["original_image_file"] = orig_filename except Exception as e: logger.warning(f"Could not save original image: {e}") # Save processed image if provided entry["has_processed_image"] = False if processed_bytes: proc_filename = f"{entry_id}_proc.{ext}" proc_path = os.path.join(IMAGES_DIR, proc_filename) try: with open(proc_path, "wb") as f: f.write(processed_bytes) entry["has_processed_image"] = True entry["processed_image_file"] = proc_filename except Exception as e: logger.warning(f"Could not save processed image: {e}") # Prepend newest first records.insert(0, entry) cls.save_all(records) logger.info(f"Saved test result {entry_id} for {entry.get('filename')} to persistent history.") return entry @classmethod def get_all(cls, limit: int = None) -> list: """Get all test results (optionally limited).""" with cls._lock: records = cls.load_all() if limit and limit > 0: return records[:limit] return records @classmethod def get_by_id(cls, entry_id: str) -> dict: """Get a single test result by ID.""" with cls._lock: records = cls.load_all() for r in records: if r.get("id") == entry_id: return r return None @classmethod def get_image_path(cls, entry_id: str, image_type: str = "original") -> str: """Return the absolute path to a saved image file if it exists.""" entry = cls.get_by_id(entry_id) if not entry: return None key = "original_image_file" if image_type == "original" else "processed_image_file" filename = entry.get(key) if filename: path = os.path.join(IMAGES_DIR, filename) if os.path.exists(path): return path return None @classmethod def delete_entry(cls, entry_id: str) -> bool: """Delete an entry and its associated stored images.""" with cls._lock: records = cls.load_all() found = False new_records = [] for r in records: if r.get("id") == entry_id: found = True # Remove saved image files for key in ("original_image_file", "processed_image_file"): fname = r.get(key) if fname: p = os.path.join(IMAGES_DIR, fname) if os.path.exists(p): try: os.remove(p) except OSError: pass else: new_records.append(r) if found: cls.save_all(new_records) logger.info(f"Deleted test entry {entry_id} from history.") return found @classmethod def clear_all(cls) -> bool: """Clear all history and remove all stored images.""" with cls._lock: cls.save_all([]) if os.path.exists(IMAGES_DIR): shutil.rmtree(IMAGES_DIR, ignore_errors=True) os.makedirs(IMAGES_DIR, exist_ok=True) logger.info("Cleared all test history and saved images.") return True @classmethod def export_csv(cls) -> str: """Export history summary as CSV string.""" with cls._lock: records = cls.load_all() output = io.StringIO() writer = csv.writer(output) headers = [ "ID", "Timestamp", "Filename", "Model", "Method", "Status", "API Response Time (s)", "Total Time (s)", "Fields Extracted", "Fields Missing", "Patient Name", "Hospital Name", "Diagnosis", "Raw Transcription Length" ] writer.writerow(headers) for r in records: res = r.get("result", {}) patient = res.get("patient_details", {}) hospital = res.get("hospital_details", {}) med = res.get("medical_details", {}) writer.writerow([ r.get("id", ""), r.get("timestamp", ""), r.get("filename", ""), r.get("model", ""), r.get("method", ""), r.get("status", ""), r.get("api_response_time", ""), r.get("total_time", ""), r.get("fields_extracted", 0), r.get("fields_missing", 0), patient.get("patient_name") or "", hospital.get("hospital_name") or "", med.get("diagnosis") or "", len(r.get("raw_transcription") or "") ]) return output.getvalue()