| 1 | #!/usr/bin/env python3 |
| 2 | # -*- coding: utf-8 -*- |
| 3 | |
| 4 | """ |
| 5 | History Manager Module |
| 6 | --------------------- |
| 7 | Manages transcription and translation history for the Online-Translator application. |
| 8 | Handles storage, retrieval, and export of historical data. |
| 9 | |
| 10 | Copyright (c) 2025 Kiko Cisneros |
| 11 | Licensed under the MIT License (see LICENSE file for details) |
| 12 | """ |
| 13 | |
| 14 | import os |
| 15 | import json |
| 16 | import csv |
| 17 | from datetime import datetime |
| 18 | from tkinter import filedialog, messagebox |
| 19 | from . import config |
| 20 | |
| 21 | |
| 22 | class TranscriptionHistory: |
| 23 | """Manages transcription history and export functionality""" |
| 24 | |
| 25 | def __init__(self): |
| 26 | self.entries = [] |
| 27 | self.current_session_start = datetime.now() |
| 28 | |
| 29 | def add_entry(self, original_text, translated_text, source_lang, target_lang): |
| 30 | """Add a new transcription entry""" |
| 31 | entry = { |
| 32 | 'timestamp': datetime.now().isoformat(), |
| 33 | 'original_text': original_text, |
| 34 | 'translated_text': translated_text, |
| 35 | 'source_language': source_lang, |
| 36 | 'target_language': target_lang |
| 37 | } |
| 38 | self.entries.append(entry) |
| 39 | |
| 40 | # Auto-save every 10 entries |
| 41 | if len(self.entries) % 10 == 0: |
| 42 | self.auto_save() |
| 43 | |
| 44 | def auto_save(self): |
| 45 | """Auto-save to a backup file (silent)""" |
| 46 | try: |
| 47 | # Create transcriptions_history folder if it doesn't exist |
| 48 | backup_folder = "transcriptions_history" |
| 49 | if not os.path.exists(backup_folder): |
| 50 | os.makedirs(backup_folder) |
| 51 | |
| 52 | backup_filename = f"transcription_backup_{self.current_session_start.strftime('%Y%m%d_%H%M%S')}.json" |
| 53 | backup_file = os.path.join(backup_folder, backup_filename) |
| 54 | |
| 55 | # Silent save without dialog |
| 56 | export_data = { |
| 57 | 'export_date': datetime.now().isoformat(), |
| 58 | 'session_start': self.current_session_start.isoformat(), |
| 59 | 'total_entries': len(self.entries), |
| 60 | 'transcriptions': self.entries |
| 61 | } |
| 62 | |
| 63 | with open(backup_file, 'w', encoding='utf-8') as f: |
| 64 | json.dump(export_data, f, indent=2, ensure_ascii=False) |
| 65 | |
| 66 | if config.ENABLE_DEBUG_LOGGING: |
| 67 | print(f"Auto-saved {len(self.entries)} entries to {backup_file}") |
| 68 | except Exception as e: |
| 69 | if config.ENABLE_DEBUG_LOGGING: |
| 70 | print(f"Auto-save error: {e}") |
| 71 | |
| 72 | def export_txt(self, filename=None): |
| 73 | """Export transcriptions as plain text""" |
| 74 | if not filename: |
| 75 | filename = filedialog.asksaveasfilename( |
| 76 | title="Export as Text", |
| 77 | defaultextension=".txt", |
| 78 | filetypes=[("Text files", "*.txt"), ("All files", "*.*")] |
| 79 | ) |
| 80 | |
| 81 | if filename: |
| 82 | try: |
| 83 | with open(filename, 'w', encoding='utf-8') as f: |
| 84 | f.write(f"Transcription Export - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") |
| 85 | f.write("=" * 60 + "\n\n") |
| 86 | |
| 87 | for i, entry in enumerate(self.entries, 1): |
| 88 | f.write(f"Entry {i} - {entry['timestamp']}\n") |
| 89 | f.write(f"Language: {entry['source_language']} → {entry['target_language']}\n") |
| 90 | f.write(f"Original: {entry['original_text']}\n") |
| 91 | f.write(f"Translation: {entry['translated_text']}\n") |
| 92 | f.write("-" * 40 + "\n\n") |
| 93 | |
| 94 | messagebox.showinfo("Export Complete", f"Exported {len(self.entries)} entries to {filename}") |
| 95 | return True |
| 96 | except Exception as e: |
| 97 | messagebox.showerror("Export Error", f"Failed to export: {e}") |
| 98 | return False |
| 99 | |
| 100 | def export_json(self, filename=None): |
| 101 | """Export transcriptions as JSON""" |
| 102 | if not filename: |
| 103 | filename = filedialog.asksaveasfilename( |
| 104 | title="Export as JSON", |
| 105 | defaultextension=".json", |
| 106 | filetypes=[("JSON files", "*.json"), ("All files", "*.*")] |
| 107 | ) |
| 108 | |
| 109 | if filename: |
| 110 | try: |
| 111 | export_data = { |
| 112 | 'export_date': datetime.now().isoformat(), |
| 113 | 'session_start': self.current_session_start.isoformat(), |
| 114 | 'total_entries': len(self.entries), |
| 115 | 'transcriptions': self.entries |
| 116 | } |
| 117 | |
| 118 | with open(filename, 'w', encoding='utf-8') as f: |
| 119 | json.dump(export_data, f, indent=2, ensure_ascii=False) |
| 120 | |
| 121 | # Only show dialog for manual exports, not auto-save |
| 122 | if filename.startswith('transcription_backup_'): |
| 123 | return True |
| 124 | else: |
| 125 | messagebox.showinfo("Export Complete", f"Exported {len(self.entries)} entries to {filename}") |
| 126 | return True |
| 127 | except Exception as e: |
| 128 | messagebox.showerror("Export Error", f"Failed to export: {e}") |
| 129 | return False |
| 130 | |
| 131 | def export_csv(self, filename=None): |
| 132 | """Export transcriptions as CSV""" |
| 133 | if not filename: |
| 134 | filename = filedialog.asksaveasfilename( |
| 135 | title="Export as CSV", |
| 136 | defaultextension=".csv", |
| 137 | filetypes=[("CSV files", "*.csv"), ("All files", "*.*")] |
| 138 | ) |
| 139 | |
| 140 | if filename: |
| 141 | try: |
| 142 | with open(filename, 'w', newline='', encoding='utf-8') as f: |
| 143 | writer = csv.writer(f) |
| 144 | writer.writerow(['Timestamp', 'Source Language', 'Target Language', 'Original Text', 'Translated Text']) |
| 145 | |
| 146 | for entry in self.entries: |
| 147 | writer.writerow([ |
| 148 | entry['timestamp'], |
| 149 | entry['source_language'], |
| 150 | entry['target_language'], |
| 151 | entry['original_text'], |
| 152 | entry['translated_text'] |
| 153 | ]) |
| 154 | |
| 155 | messagebox.showinfo("Export Complete", f"Exported {len(self.entries)} entries to {filename}") |
| 156 | return True |
| 157 | except Exception as e: |
| 158 | messagebox.showerror("Export Error", f"Failed to export: {e}") |
| 159 | return False |
| 160 | |
| 161 | def clear_history(self): |
| 162 | """Clear all transcription history""" |
| 163 | self.entries.clear() |
| 164 | self.current_session_start = datetime.now() |