gelpredict / app /sync_manager.py
awolter's picture
Upload folder using huggingface_hub
9b6c735 verified
Raw History Blame Contribute Delete
58.6 kB
""" GelPredict Multi-Computer Sync Manager - Conflict-free merge: NEVER overwrites data - Append-only sync: new records are merged in - Safe deletes: requires explicit confirmation - Cloud storage options: Dropbox, Google Drive, OneDrive, Git - Backup before every sync - Folder picker for easy setup """ from __future__ import annotations import streamlit as st import sqlite3 import pandas as pd import shutil from pathlib import Path from datetime import datetime import hashlib import json import subprocess import platform import os ROOT = Path(__file__).resolve().parents[1] # Sync configuration SYNC_CONFIG_FILE = ROOT / "sync_config.json" SYNC_BACKUP_DIR = ROOT / "sync_backups" SYNC_BACKUP_DIR.mkdir(exist_ok=True) # All databases to sync DATABASES = { "lab_hydrogels": ROOT / "gelpredict.db", "lit_hydrogels": ROOT / "data" / "reference_db.sqlite", "lab_cellgrowth": ROOT / "data" / "cellgrowth_lab.sqlite", "lit_cellgrowth": ROOT / "data" / "cellgrowth_lit.sqlite", "lab_morphology": ROOT / "data" / "morphology_lab.sqlite", "lit_morphology": ROOT / "data" / "morphology_literature.sqlite", } # Tables to sync (append-only) SYNC_TABLES = { "gelpredict.db": ["wells_master_v4", "reagents_per_well", "events_long", "gel_images", "plates_registry"], "reference_db.sqlite": ["literature_wells", "literature_images"], "cellgrowth_lab.sqlite": ["cell_runs", "cell_run_hydrogels", "cell_media_components", "cell_events", "cell_images"], "cellgrowth_lit.sqlite": ["lit_cell_runs", "lit_cell_run_hydrogels", "lit_media_components", "lit_cell_events", "lit_cell_images"], "morphology_lab.sqlite": ["morphology_observations", "morphology_images", "marker_staining"], "morphology_literature.sqlite": ["lit_morphology_observations", "lit_morphology_images", "lit_marker_staining"], } # ---------------- CSV Export Functions ---------------- def export_database_to_csv(db_path: Path, remote_root: Path) -> dict: """Export SQLite database tables to CSV files in the remote sync folder.""" if not db_path.exists(): return {"error": f"Database not found: {db_path}"} stats = {"exported": 0, "errors": []} db_name = db_path.stem # e.g., "gelpredict" from "gelpredict.db" csv_dir = remote_root / f"{db_name}_csv" csv_dir.mkdir(parents=True, exist_ok=True) try: with sqlite3.connect(db_path) as conn: # Get all table names cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = [row[0] for row in cursor.fetchall()] for table in tables: try: # Export table to CSV df = pd.read_sql_query(f"SELECT * FROM {table}", conn) csv_path = csv_dir / f"{table}.csv" df.to_csv(csv_path, index=False) stats["exported"] += 1 st.caption(f" πŸ“„ Exported {table}.csv ({len(df)} rows)") except Exception as e: stats["errors"].append(f"{table}: {e}") except Exception as e: stats["errors"].append(f"Database connection: {e}") return stats # ---------------- Sync Configuration ---------------- def load_sync_config() -> dict: """Load sync configuration from JSON file.""" # Check if running on Railway (cloud deployment) is_railway = os.getenv("RAILWAY_ENVIRONMENT") is not None if SYNC_CONFIG_FILE.exists() and not is_railway: with open(SYNC_CONFIG_FILE) as f: return json.load(f) # Default config - disable sync on Railway config = { "sync_method": "none", # 'none' | 'dropbox' | 'gdrive' | 'onedrive' | 'git' | 'network_drive' "sync_folder": "", "last_sync": None, "computer_id": hashlib.md5(str(ROOT).encode()).hexdigest()[:8], # Unique ID for this computer "is_railway": is_railway, } if is_railway: # Keep sync_method as "none" by default, user can choose cloud options config["railway_message"] = "Cloud sync available - use OneDrive API or manual upload/download" return config def save_sync_config(config: dict): """Save sync configuration.""" with open(SYNC_CONFIG_FILE, "w") as f: json.dump(config, f, indent=2) # ---------------- Folder Picker ---------------- def open_folder_picker(title: str = "Select Sync Folder") -> str | None: """ Open native folder picker dialog. Returns selected folder path or None if cancelled. Note: In cloud environments (like Railway), this will return None and users should use manual path entry instead. """ # Check if we're in a cloud environment if is_cloud_environment(): st.warning("⚠️ Folder picker not available in cloud environment. Please use manual path entry below.") return None system = platform.system() try: if system == "Darwin": # macOS # Use AppleScript for folder picker script = f''' tell application "System Events" activate set folderPath to choose folder with prompt "{title}" return POSIX path of folderPath end tell ''' result = subprocess.run( ["osascript", "-e", script], capture_output=True, text=True, timeout=300 # 5 minute timeout ) if result.returncode == 0 and result.stdout.strip(): return result.stdout.strip() elif system == "Windows": # Use PowerShell folder picker script = f''' Add-Type -AssemblyName System.Windows.Forms $folder = New-Object System.Windows.Forms.FolderBrowserDialog $folder.Description = "{title}" $folder.ShowNewFolderButton = $true if ($folder.ShowDialog() -eq "OK") {{ Write-Output $folder.SelectedPath }} ''' result = subprocess.run( ["powershell", "-Command", script], capture_output=True, text=True, timeout=300 ) if result.returncode == 0 and result.stdout.strip(): return result.stdout.strip() elif system == "Linux": # Try zenity (common on Linux) - but only if not in cloud try: result = subprocess.run( ["zenity", "--file-selection", "--directory", f"--title={title}"], capture_output=True, text=True, timeout=300 ) if result.returncode == 0 and result.stdout.strip(): return result.stdout.strip() except FileNotFoundError: st.warning("⚠️ zenity not available. Please use manual path entry below.") return None except Exception as e: st.error(f"Folder picker error: {e}") return None def is_cloud_environment() -> bool: """ Detect if we're running in a cloud environment (Railway, Heroku, etc.) """ # Check for common cloud environment variables cloud_indicators = [ "RAILWAY_ENVIRONMENT", # Railway "HEROKU_APP_NAME", # Heroku "VERCEL", # Vercel "AWS_LAMBDA_FUNCTION_NAME", # AWS Lambda "GOOGLE_CLOUD_PROJECT", # Google Cloud "AZURE_FUNCTIONS_ENVIRONMENT", # Azure ] return any(os.getenv(indicator) for indicator in cloud_indicators) def check_onedrive_sync_status(sync_folder: str) -> dict: """ Check if OneDrive is actively syncing the specified folder. Returns status information for user feedback. """ import os import time status = { "onedrive_running": False, "folder_syncing": False, "last_sync_time": None, "sync_status": "unknown", "recommendations": [] } try: # Check if OneDrive process is running system = platform.system() if system == "Windows": import subprocess try: result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq OneDrive.exe'], capture_output=True, text=True, timeout=5) status["onedrive_running"] = "OneDrive.exe" in result.stdout except: status["onedrive_running"] = False elif system == "Darwin": # macOS import subprocess try: result = subprocess.run(['pgrep', '-f', 'OneDrive'], capture_output=True, text=True, timeout=5) status["onedrive_running"] = bool(result.stdout.strip()) except: status["onedrive_running"] = False # Check folder sync status if os.path.exists(sync_folder): # Check if folder is in OneDrive sync directory sync_folder_path = Path(sync_folder) if "OneDrive" in str(sync_folder_path): status["folder_syncing"] = True status["sync_status"] = "configured" # Check last modification time try: stat = sync_folder_path.stat() status["last_sync_time"] = time.ctime(stat.st_mtime) except: pass else: status["sync_status"] = "not_in_onedrive" status["recommendations"].append("Move sync folder to OneDrive directory") else: status["sync_status"] = "folder_not_found" status["recommendations"].append("Create sync folder first") # Generate recommendations if not status["onedrive_running"]: status["recommendations"].append("Start OneDrive application") if status["onedrive_running"] and status["folder_syncing"]: status["sync_status"] = "ready" except Exception as e: status["sync_status"] = "error" status["recommendations"].append(f"Error checking status: {e}") return status def detect_onedrive_path() -> str | None: """ Auto-detect OneDrive folder path on this computer. Returns None if not found. """ import os system = platform.system() home = Path.home() # Common OneDrive locations candidates = [ home / "OneDrive", home / "OneDrive - Personal", home / "OneDrive - Old Dominion University", ] # Windows-specific if system == "Windows": candidates.extend([ Path(f"C:/Users/{home.name}/OneDrive"), Path(f"C:/Users/{home.name}/OneDrive - Personal"), ]) # Check each candidate for path in candidates: if path.exists() and path.is_dir(): # Use proper path joining for the platform if system == "Windows": return os.path.join(str(path), "GelPredict_Sync") else: return str(path / "GelPredict_Sync") return None # ---------------- Backup Before Sync ---------------- def create_pre_sync_backup(db_path: Path) -> Path: """Create timestamped backup before syncing.""" timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") backup_name = f"{db_path.stem}_presync_{timestamp}.sqlite" backup_path = SYNC_BACKUP_DIR / backup_name shutil.copy2(db_path, backup_path) return backup_path # ---------------- Conflict-Free Merge ---------------- def get_table_primary_key(con: sqlite3.Connection, table: str) -> str | None: """Get primary key column name for a table.""" pragma = con.execute(f"PRAGMA table_info({table})").fetchall() for row in pragma: if row[5] == 1: # pk column is index 5 in pragma result return row[1] # name is index 1 return None def merge_tables_append_only(local_db: Path, remote_db: Path, tables: list[str]) -> dict: """ Merge remote database into local using append-only strategy. NEVER overwrites existing records. Returns merge statistics. """ stats = {"added": 0, "skipped": 0, "errors": []} local_con = sqlite3.connect(str(local_db)) local_con.row_factory = sqlite3.Row remote_con = sqlite3.connect(str(remote_db)) remote_con.row_factory = sqlite3.Row try: for table in tables: # Check if table exists in both databases local_tables = {r[0] for r in local_con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()} remote_tables = {r[0] for r in remote_con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()} if table not in local_tables or table not in remote_tables: stats["skipped"] += 1 continue # Get primary key pk = get_table_primary_key(local_con, table) if not pk: stats["errors"].append(f"{table}: No primary key found") continue # Get all remote records remote_df = pd.read_sql_query(f"SELECT * FROM {table}", remote_con) if remote_df.empty: continue # Get existing local primary keys local_pks = {r[0] for r in local_con.execute(f"SELECT {pk} FROM {table}").fetchall()} # Insert only new records (append-only) for _, row in remote_df.iterrows(): row_pk = row[pk] if row_pk not in local_pks: # Insert new record cols = list(row.index) vals = [row[c] for c in cols] placeholders = ",".join(["?"] * len(cols)) try: local_con.execute(f"INSERT INTO {table}({','.join(cols)}) VALUES({placeholders})", vals) stats["added"] += 1 except Exception as e: stats["errors"].append(f"{table}.{row_pk}: {e}") else: stats["skipped"] += 1 local_con.commit() finally: local_con.close() remote_con.close() return stats # ---------------- Image Sync ---------------- def sync_images(local_folder: Path, remote_folder: Path) -> dict: """ Sync images from remote to local (append-only). Compares by filename and SHA256 hash. """ stats = {"added": 0, "skipped": 0, "errors": []} if not remote_folder.exists(): return stats local_folder.mkdir(parents=True, exist_ok=True) # Get local images and their hashes local_images = {} for img in local_folder.glob("*"): if img.is_file(): local_images[img.name] = _hash_file(img) # Copy new images from remote for remote_img in remote_folder.glob("*"): if remote_img.is_file(): remote_hash = _hash_file(remote_img) if remote_img.name not in local_images: # New image - copy it shutil.copy2(remote_img, local_folder / remote_img.name) stats["added"] += 1 elif local_images[remote_img.name] != remote_hash: # Same name, different content - keep both new_name = f"{remote_img.stem}_remote_{remote_hash[:8]}{remote_img.suffix}" shutil.copy2(remote_img, local_folder / new_name) stats["added"] += 1 else: # Identical file stats["skipped"] += 1 return stats def _hash_file(path: Path) -> str: """Compute SHA256 hash of a file.""" sha256 = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): sha256.update(chunk) return sha256.hexdigest() # ---------------- Sync Methods ---------------- def sync_from_folder(remote_root: Path, config: dict = None) -> dict: """ Sync from a remote folder (Dropbox, Google Drive, network drive, etc.). Merges databases and images using append-only strategy. """ total_stats = {"databases": {}, "images": {}, "errors": []} # Check if remote folder exists and is accessible try: if not remote_root.exists(): total_stats["errors"].append(f"Remote folder not found: {remote_root}") return total_stats if not remote_root.is_dir(): total_stats["errors"].append(f"Remote path is not a directory: {remote_root}") return total_stats # Check read permissions if not os.access(remote_root, os.R_OK): total_stats["errors"].append(f"No read permission for remote folder: {remote_root}") return total_stats except Exception as e: total_stats["errors"].append(f"Error accessing remote folder: {e}") return total_stats # 1. Backup local databases first st.info("πŸ“¦ Creating pre-sync backups...") for name, db_path in DATABASES.items(): if db_path.exists(): backup_path = create_pre_sync_backup(db_path) st.caption(f"Backed up {name} β†’ {backup_path.name}") # 2. Sync databases st.info("πŸ”„ Merging databases (append-only)...") for name, local_db in DATABASES.items(): remote_db = remote_root / local_db.relative_to(ROOT) if not remote_db.exists(): st.warning(f"⚠️ Remote database not found: {remote_db}") continue if not local_db.exists(): # First time - just copy local_db.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(remote_db, local_db) total_stats["databases"][name] = {"added": "all", "skipped": 0} st.success(f"βœ… Initialized {name} from remote") else: # Merge db_file_name = local_db.name tables = SYNC_TABLES.get(db_file_name, []) stats = merge_tables_append_only(local_db, remote_db, tables) total_stats["databases"][name] = stats if stats["added"] > 0: st.success(f"βœ… {name}: Added {stats['added']} records, skipped {stats['skipped']}") else: st.info(f"ℹ️ {name}: No new records (skipped {stats['skipped']})") if stats["errors"]: with st.expander(f"⚠️ Errors in {name}"): for err in stats["errors"]: st.error(err) # Export CSV files for this database (from local after pull, if enabled) if config.get("export_csv", True): st.caption(f"πŸ“„ Exporting CSV files for {name}...") csv_stats = export_database_to_csv(local_db, ROOT) if csv_stats.get("exported", 0) > 0: st.success(f"βœ… Exported {csv_stats['exported']} CSV files for {name}") if csv_stats.get("errors"): for error in csv_stats["errors"]: st.warning(f"⚠️ CSV export warning: {error}") # 3. Sync images st.info("πŸ–ΌοΈ Syncing images (append-only)...") image_folders = [ "media/images/lab_hydrogels", "media/images/literature_hydrogels", "media/images/lab_cells", "media/images/literature_cells", "media/images/lab_morphology", "media/images/literature_morphology", ] for folder in image_folders: local_folder = ROOT / folder remote_folder = remote_root / folder img_stats = sync_images(local_folder, remote_folder) total_stats["images"][folder] = img_stats if img_stats["added"] > 0: st.success(f"βœ… {folder}: Added {img_stats['added']} images") return total_stats def push_to_folder(remote_root: Path, config: dict = None) -> dict: """ Push local data to remote folder (append-only). Remote will merge local changes without overwriting. """ total_stats = {"databases": {}, "images": {}, "errors": []} st.info("πŸ“€ Pushing local data to remote (append-only)...") # 1. Ensure remote directory exists remote_root.mkdir(parents=True, exist_ok=True) # 2. For each database, merge local β†’ remote for name, local_db in DATABASES.items(): if not local_db.exists(): continue remote_db = remote_root / local_db.relative_to(ROOT) remote_db.parent.mkdir(parents=True, exist_ok=True) if not remote_db.exists(): # First time - just copy st.info(f"πŸ“‹ Copying {local_db.name}...") st.caption(f" FROM: `{local_db}`") st.caption(f" TO: `{remote_db}`") shutil.copy2(local_db, remote_db) # Verify it was created if remote_db.exists(): size = remote_db.stat().st_size / 1024 st.success(f"βœ… Created {name} ({size:.1f} KB)") st.success(f" πŸ“ Location: `{remote_db}`") else: st.error(f"❌ Failed to create {remote_db}") total_stats["databases"][name] = {"added": "all"} else: # Merge local into remote db_file_name = local_db.name tables = SYNC_TABLES.get(db_file_name, []) stats = merge_tables_append_only(remote_db, local_db, tables) total_stats["databases"][name] = stats if stats["added"] > 0: st.success(f"βœ… {name}: Pushed {stats['added']} records") # Export CSV files for this database (if enabled) if config.get("export_csv", True): st.caption(f"πŸ“„ Exporting CSV files for {name}...") csv_stats = export_database_to_csv(remote_db, remote_root) if csv_stats.get("exported", 0) > 0: st.success(f"βœ… Exported {csv_stats['exported']} CSV files for {name}") if csv_stats.get("errors"): for error in csv_stats["errors"]: st.warning(f"⚠️ CSV export warning: {error}") # 3. Push images image_folders = [ "media/images/lab_hydrogels", "media/images/literature_hydrogels", "media/images/lab_cells", "media/images/literature_cells", "media/images/lab_morphology", "media/images/literature_morphology", ] for folder in image_folders: local_folder = ROOT / folder remote_folder = remote_root / folder if local_folder.exists(): img_stats = sync_images(remote_folder, local_folder) total_stats["images"][folder] = img_stats if img_stats["added"] > 0: st.success(f"βœ… {folder}: Pushed {img_stats['added']} images") return total_stats # ---------------- Safe Delete with Confirmation ---------------- def show_delete_interface(): """Show interface for deleting records with multi-step confirmation.""" st.header("πŸ—‘οΈ Safe Delete (with confirmation)") st.warning("⚠️ Deletes are permanent and will sync to other computers!") # Select database db_choice = st.selectbox("Select Database", list(DATABASES.keys())) db_path = DATABASES[db_choice] if not db_path.exists(): st.info(f"Database {db_path.name} doesn't exist yet.") return # Select table con = sqlite3.connect(str(db_path)) tables = [r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").fetchall()] con.close() table = st.selectbox("Select Table", tables) # Load records con = sqlite3.connect(str(db_path)) df = pd.read_sql_query(f"SELECT * FROM {table} LIMIT 500", con) con.close() if df.empty: st.info(f"No records in {table}") return st.dataframe(df, use_container_width=True, height=300) # Get primary key column pk_cols = [c for c in df.columns if 'id' in c.lower()] if not pk_cols: st.error("Cannot identify primary key column") return pk_col = pk_cols[0] # Select record to delete st.markdown("---") st.subheader("⚠️ Delete Record") record_id = st.selectbox( "Select Record to Delete", [""] + df[pk_col].tolist(), format_func=lambda x: f"{x[:30]}..." if len(str(x)) > 30 else str(x) if x else "Select record" ) if record_id: # Show record details record = df[df[pk_col] == record_id].iloc[0] st.json(record.to_dict()) st.markdown("---") st.error("🚨 PERMANENT DELETE - This action cannot be undone!") # Multi-step confirmation col1, col2 = st.columns(2) with col1: confirm1 = st.checkbox("I understand this is permanent") with col2: confirm2 = st.checkbox("I want to delete this record") type_to_confirm = st.text_input( "Type DELETE to confirm", help="Type the word DELETE in all caps" ) if confirm1 and confirm2 and type_to_confirm == "DELETE": if st.button("πŸ—‘οΈ DELETE RECORD", type="primary"): try: # Create backup first backup = create_pre_sync_backup(db_path) st.info(f"Backup created: {backup.name}") # Perform delete con = sqlite3.connect(str(db_path)) con.execute(f"DELETE FROM {table} WHERE {pk_col} = ?", (record_id,)) con.commit() rows_deleted = con.total_changes con.close() st.success(f"βœ… Deleted {rows_deleted} row(s)") st.balloons() # Log deletion with open(ROOT / "deletion_log.txt", "a") as f: f.write(f"{datetime.now().isoformat()} | {db_choice} | {table} | {pk_col}={record_id}\n") st.rerun() except Exception as e: st.error(f"❌ Delete failed: {e}") else: st.caption("Complete all confirmations above to enable delete button") # ---------------- UI ---------------- def show_sync_app(): st.title("πŸ”„ GelPredict Multi-Computer Sync Manager") st.caption("Conflict-free data merging across computers β€’ Append-only β€’ Never overwrites") # Cloud environment notice if is_cloud_environment(): st.info("🌐 **Cloud Environment**: You're running GelPredict on a cloud platform (Railway, etc.). Folder picker dialogs are not available - please use manual path entry instead.") # Railway-specific sync notice config = load_sync_config() if config.get("is_railway"): if config.get("sync_method") in ["onedrive_api", "manual_upload", "cloud_database"]: st.success("πŸš‚ **Railway Cloud Sync**: Cloud sync is enabled! Choose your preferred sync method below.") else: st.info("πŸš‚ **Railway Deployment**: Cloud sync is available! Configure OneDrive API, manual upload/download, or cloud database sync.") # OneDrive sync status check (for local sync methods) if config.get("sync_method") in ["onedrive", "dropbox", "gdrive"] and config.get("sync_folder"): with st.expander("πŸ” OneDrive Sync Status", expanded=False): status = check_onedrive_sync_status(config["sync_folder"]) if status["sync_status"] == "ready": st.success("βœ… **OneDrive Ready**: Sync folder is properly configured and OneDrive is running") if status["last_sync_time"]: st.caption(f"πŸ“… Last sync: {status['last_sync_time']}") elif status["sync_status"] == "configured": st.warning("⚠️ **OneDrive Configured**: Folder is in OneDrive but OneDrive app may not be running") st.caption("πŸ’‘ Make sure OneDrive is running and syncing") elif status["sync_status"] == "not_in_onedrive": st.error("❌ **Not in OneDrive**: Sync folder is not in OneDrive directory") st.caption("πŸ’‘ Move your sync folder to OneDrive for automatic cloud sync") elif status["sync_status"] == "folder_not_found": st.error("❌ **Folder Not Found**: Sync folder does not exist") st.caption("πŸ’‘ Create the sync folder first") else: st.info("ℹ️ **Status Unknown**: Could not determine OneDrive sync status") if status["recommendations"]: st.markdown("**Recommendations:**") for rec in status["recommendations"]: st.markdown(f"β€’ {rec}") # Sidebar: Sync status st.sidebar.markdown("### πŸ’» Computer ID") st.sidebar.code(config["computer_id"]) st.sidebar.caption("Unique ID for this computer") if config.get("last_sync"): st.sidebar.markdown("### πŸ• Last Sync") st.sidebar.info(config["last_sync"]) st.sidebar.markdown("---") # Main tabs - show cloud sync options on Railway if config.get("is_railway"): if config.get("sync_method") in ["onedrive_api", "manual_upload", "cloud_database"]: tab1, tab2, tab3, tab4 = st.tabs(["βš™οΈ Setup", "⬇️ Pull (Sync In)", "⬆️ Push (Sync Out)", "πŸ—‘οΈ Safe Delete"]) else: tab1, tab2, tab3, tab4 = st.tabs(["βš™οΈ Setup", "☁️ Cloud Sync", "☁️ Cloud Sync", "☁️ Cloud Sync"]) else: tab1, tab2, tab3, tab4 = st.tabs(["βš™οΈ Setup", "⬇️ Pull (Sync In)", "⬆️ Push (Sync Out)", "πŸ—‘οΈ Safe Delete"]) # ===== SETUP TAB ===== with tab1: st.header("βš™οΈ Sync Setup") st.markdown("Configure how you want to sync data across computers") # Railway-specific sync options if config.get("is_railway") or config.get("sync_method") in ["railway_cloud", "railway_disabled"]: # Map railway_cloud to none for the radio button current_method = config.get("sync_method", "none") if current_method in ["railway_cloud", "railway_disabled"]: current_method = "none" # Ensure current method is valid valid_methods = ["none", "onedrive_api", "manual_upload", "cloud_database"] if current_method not in valid_methods: current_method = "none" sync_method = st.radio( "Sync Method", valid_methods, index=valid_methods.index(current_method), format_func=lambda x: { "none": "❌ No Sync", "onedrive_api": "☁️ OneDrive API (Cloud)", "manual_upload": "πŸ“€ Manual Upload/Download", "cloud_database": "πŸ—„οΈ Cloud Database" }[x] ) else: # Ensure current method is valid for local sync current_method = config.get("sync_method", "none") valid_methods = ["none", "dropbox", "gdrive", "onedrive", "network_drive", "git"] if current_method not in valid_methods: current_method = "none" sync_method = st.radio( "Sync Method", valid_methods, index=valid_methods.index(current_method), format_func=lambda x: { "none": "❌ No Sync (Local Only)", "dropbox": "πŸ“¦ Dropbox", "gdrive": "☁️ Google Drive", "onedrive": "☁️ OneDrive", "network_drive": "πŸ–₯️ Network Drive", "git": "πŸ”§ Git (Advanced)" }[x] ) # Cloud sync configuration if sync_method == "onedrive_api": st.markdown("### ☁️ OneDrive API Configuration") st.info("πŸš€ **OneDrive API Sync**: Direct cloud-to-cloud sync using Microsoft Graph API") st.markdown("**Setup Steps:**") st.markdown(""" 1. **Register App**: Go to [Azure Portal](https://portal.azure.com) β†’ App registrations β†’ New registration 2. **Get Credentials**: Copy Application (client) ID and create a client secret 3. **Set Permissions**: Add Microsoft Graph API permissions (Files.ReadWrite) 4. **Enter Credentials**: Fill in the fields below """) client_id = st.text_input("Application (Client) ID", placeholder="12345678-1234-1234-1234-123456789012") client_secret = st.text_input("Client Secret", type="password", placeholder="Enter your client secret") tenant_id = st.text_input("Directory (Tenant) ID", placeholder="12345678-1234-1234-1234-123456789012") # Platform-appropriate path placeholder import os if os.name == 'nt': # Windows folder_placeholder = "\\GelPredict_Sync" folder_help = "Path within your OneDrive root (Windows style with backslashes)" else: # macOS/Linux folder_placeholder = "/GelPredict_Sync" folder_help = "Path within your OneDrive root (Unix style with forward slashes)" folder_path = st.text_input("OneDrive Folder Path", placeholder=folder_placeholder, help=folder_help) if client_id and client_secret and tenant_id: st.success("βœ… Configuration complete! Click 'Test Connection' below.") elif sync_method == "manual_upload": st.markdown("### πŸ“€ Manual Upload/Download") st.info("πŸ’‘ **Manual Sync**: Upload/download database files manually") st.markdown("**How it works:**") st.markdown(""" 1. **Download**: Export your database files from Railway 2. **Transfer**: Upload to your OneDrive/cloud storage 3. **Import**: Download and import on other computers 4. **Sync**: Repeat as needed """) st.markdown("**Benefits:**") st.markdown("- βœ… Works with any cloud storage") st.markdown("- βœ… No API setup required") st.markdown("- βœ… Full control over sync timing") st.markdown("- βœ… Works offline") elif sync_method == "cloud_database": st.markdown("### πŸ—„οΈ Cloud Database Configuration") st.info("🌐 **Cloud Database**: Connect to a remote database for real-time sync") st.markdown("**Supported Databases:**") st.markdown("- PostgreSQL (Railway, Supabase, etc.)") st.markdown("- MySQL (PlanetScale, etc.)") st.markdown("- SQLite (Cloud storage)") db_type = st.selectbox("Database Type", ["postgresql", "mysql", "sqlite"]) db_url = st.text_input("Database URL", placeholder="postgresql://user:pass@host:port/dbname", type="password") if db_url: st.success("βœ… Database URL configured! Test connection below.") elif sync_method not in ["none", "railway_disabled"]: st.markdown("### Sync Folder Location") st.caption("This folder should be in your cloud storage (OneDrive, Dropbox, Google Drive, etc.)") # Auto-detect OneDrive for convenience detected_path = detect_onedrive_path() if sync_method == "onedrive" else None # Current sync folder (from config or detected) current_folder = config.get("sync_folder", detected_path or "") # Check if folder picker was just used if st.session_state.get("open_picker"): # Skip folder picker on Railway if config.get("is_railway") or config.get("sync_method") == "railway_disabled": st.info("πŸš‚ **Railway Environment**: Sync is disabled, folder picker not needed.") st.session_state["open_picker"] = False elif is_cloud_environment(): st.info("🌐 **Cloud Environment Detected**") st.warning("⚠️ Folder picker is not available in cloud environments (Railway, etc.)") st.info("πŸ’‘ **Please use manual path entry below instead.**") st.caption("Enter the full path to your OneDrive/cloud storage folder manually.") st.session_state["open_picker"] = False else: st.info("πŸ” Opening folder picker dialog...") st.caption("Select your OneDrive/cloud storage folder in the dialog that appears") picked_folder = open_folder_picker(f"Select {sync_method.upper()} Sync Folder") if picked_folder: st.session_state["picked_sync_folder"] = picked_folder st.success(f"βœ… Selected: {picked_folder}") st.session_state["open_picker"] = False st.rerun() else: st.warning("No folder selected (picker cancelled)") st.session_state["open_picker"] = False # Determine default value (picked folder takes precedence, then detected path) if st.session_state.get("use_detected_path", False): default_folder = detected_path or "" st.session_state["use_detected_path"] = False # Reset flag else: default_folder = st.session_state.get("picked_sync_folder", current_folder or "") # Debug info if default_folder: st.caption(f"πŸ” Default folder: `{default_folder}`") # Display path input with browse button col_path, col_btn = st.columns([3, 1]) with col_path: sync_folder = st.text_input( "Sync Folder Path", value=default_folder, help="Click 'Browse' to select folder or paste path directly", key="sync_folder_input" ) with col_btn: # Disable browse button on Railway if config.get("is_railway") or config.get("sync_method") == "railway_disabled": st.button("πŸ“ Browse...", use_container_width=True, disabled=True, help="Browse disabled on Railway") else: if st.button("πŸ“ Browse...", use_container_width=True, help="Open folder picker"): st.session_state["open_picker"] = True st.rerun() # Option to create subfolder use_subfolder = st.checkbox( "πŸ“ Create 'GelPredict_Sync' subfolder", value=True, help="Recommended - keeps sync data organized in a dedicated subfolder" ) # Option to export CSV files export_csv = st.checkbox( "πŸ“„ Export CSV files", value=True, help="Export database tables as CSV files for easier sharing and Excel analysis" ) if use_subfolder and sync_folder: # Use proper path joining for the platform import os if os.name == 'nt': # Windows actual_sync_path = os.path.join(sync_folder, "GelPredict_Sync") else: # macOS/Linux actual_sync_path = Path(sync_folder) / "GelPredict_Sync" st.caption(f"πŸ“‚ Actual sync location: `{actual_sync_path}`") else: actual_sync_path = Path(sync_folder) if sync_folder else None st.caption(f"πŸ“‚ Files will sync directly to: `{sync_folder}`") # Auto-detect suggestion if sync_method == "onedrive" and detected_path and sync_folder != detected_path: st.info(f"πŸ’‘ OneDrive detected at: `{detected_path}`") col_use, col_copy = st.columns(2) with col_use: # Disable on Railway if config.get("is_railway") or config.get("sync_method") == "railway_disabled": st.button("✨ Use Detected Path", disabled=True, help="Disabled on Railway") else: if st.button("✨ Use Detected Path"): st.session_state["picked_sync_folder"] = detected_path st.session_state["use_detected_path"] = True st.rerun() with col_copy: if st.button("πŸ“‹ Copy to Clipboard"): st.write("Copy this path and paste it in the text field below:") st.code(detected_path) # Direct path input as fallback st.markdown("**Or enter the path directly:**") direct_path = st.text_input( "Direct Path Entry", value=detected_path, help="Enter the sync folder path directly", key="direct_path_input" ) if direct_path and direct_path != sync_folder: st.session_state["picked_sync_folder"] = direct_path st.success(f"βœ… Path set: `{direct_path}`") st.rerun() # Test folder access if sync_folder: test_path = Path(sync_folder) col_test, col_create = st.columns(2) with col_test: if st.button("πŸ” Test Access", use_container_width=True): if test_path.exists(): st.success(f"βœ… Folder exists and is accessible") # Show contents try: contents = list(test_path.iterdir())[:10] if contents: st.caption(f"Contains {len(list(test_path.iterdir()))} items") else: st.caption("Folder is empty (ready for first sync)") except Exception: pass else: st.warning(f"⚠️ Folder doesn't exist yet") with col_create: if not test_path.exists(): if st.button("πŸ“ Create Folder", type="primary", use_container_width=True): try: test_path.mkdir(parents=True, exist_ok=True) st.success(f"βœ… Created sync folder!") st.balloons() except Exception as e: st.error(f"Failed to create folder: {e}") # Save configuration if st.button("πŸ’Ύ Save Sync Configuration", type="primary"): # Validate path first if not sync_folder or sync_folder.strip() == "": st.error("❌ Please enter or select a sync folder path") elif ".Trash" in str(sync_folder): st.error("❌ Cannot sync to Trash folder! Please select a valid folder.") st.warning("πŸ’‘ Tip: Select your OneDrive folder, not Trash") else: # Determine final sync path final_sync_path = str(actual_sync_path) if use_subfolder and sync_folder else sync_folder config["sync_method"] = sync_method config["sync_folder"] = final_sync_path config["use_subfolder"] = use_subfolder config["export_csv"] = export_csv save_sync_config(config) st.success("βœ… Sync configuration saved!") st.success(f"πŸ“ Sync location: `{final_sync_path}`") # Instructions st.markdown("---") st.markdown("### πŸ“˜ How It Works") st.info(""" **Append-Only Merge Strategy:** - βœ… New records from remote are added to local - βœ… Existing records are never overwritten - βœ… Both computers keep all data - βœ… No conflicts possible! **Workflow:** 1. Computer A: Enter data β†’ Push to sync folder 2. Computer B: Pull from sync folder β†’ Gets Computer A's data 3. Computer B: Enter more data β†’ Push to sync folder 4. Computer A: Pull from sync folder β†’ Gets Computer B's data **Result:** Both computers have all data from both! """) # ===== PULL TAB ===== with tab2: if config.get("is_railway") and config.get("sync_method") == "manual_upload": st.header("⬇️ Download Data (Manual Sync)") st.info("πŸ“€ **Manual Download**: Download database files to sync with your local computer or OneDrive") # Create downloadable files st.markdown("### πŸ“₯ Download Database Files") # Create a zip file with all databases import zipfile import io zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file: for name, db_path in DATABASES.items(): if db_path.exists(): zip_file.write(db_path, f"{name}.sqlite") st.write(f"βœ… {name}: {db_path.stat().st_size / 1024:.1f} KB") else: st.write(f"⚠️ {name}: Not found") zip_buffer.seek(0) st.download_button( label="πŸ“¦ Download All Databases (ZIP)", data=zip_buffer.getvalue(), file_name=f"GelPredict_Databases_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip", mime="application/zip", use_container_width=True ) st.markdown("### πŸ“‹ Instructions") st.markdown(""" 1. **Download** the ZIP file above 2. **Extract** to your local computer 3. **Upload** to your OneDrive folder 4. **Import** into your local GelPredict installation 5. **Sync** with other computers using local OneDrive sync """) elif config.get("is_railway") and config.get("sync_method") not in ["onedrive_api", "manual_upload", "cloud_database"]: st.header("☁️ Cloud Sync Options") st.info("πŸš‚ **Railway Cloud Sync**: Choose a sync method in the Setup tab") st.markdown("**Available options:**") st.markdown("- ☁️ **OneDrive API**: Direct cloud-to-cloud sync") st.markdown("- πŸ“€ **Manual Upload/Download**: Export/import database files") st.markdown("- πŸ—„οΈ **Cloud Database**: Connect to remote database") elif config.get("is_railway") or config.get("sync_method") == "railway_disabled": st.header("🚫 Sync Disabled on Railway") st.warning("πŸš‚ **Railway Limitation**: OneDrive sync is not available on Railway deployments.") st.info(""" **Why sync doesn't work on Railway:** - Railway runs on remote cloud servers - These servers can't access your local OneDrive folders - Sync requires local file system access **Solutions:** 1. **Use local GelPredict**: Run `streamlit run app/data_entry_gui.py` locally for OneDrive sync 2. **Export/Import**: Export data from Railway and import into local version 3. **Git sync**: Use git for code changes (but not database data) """) else: st.header("⬇️ Pull Data from Remote (Sync In)") st.caption("Merge remote data into this computer without overwriting anything") if config["sync_method"] == "none": st.warning("⚠️ Configure sync method in Setup tab first") else: remote_root = Path(config["sync_folder"]) if not remote_root.exists(): st.error(f"❌ Remote folder not found: {remote_root}") st.info("Make sure the sync folder exists and is accessible") else: st.success(f"βœ… Remote folder: {remote_root}") # Preview what will be synced st.markdown("### πŸ“Š Preview") for name, local_db in DATABASES.items(): remote_db = remote_root / local_db.relative_to(ROOT) if remote_db.exists(): remote_size = remote_db.stat().st_size / 1024 # KB local_size = local_db.stat().st_size / 1024 if local_db.exists() else 0 st.write(f"- {name}: Remote {remote_size:.1f} KB β†’ Local {local_size:.1f} KB") # Perform sync st.markdown("---") if st.button("πŸ”„ PULL DATA FROM REMOTE", type="primary", use_container_width=True): with st.spinner("Syncing..."): stats = sync_from_folder(remote_root, config) # Update last sync time config["last_sync"] = datetime.now().isoformat() save_sync_config(config) st.success("βœ… Sync complete!") # Show summary total_added = sum(s.get("added", 0) for s in stats["databases"].values() if isinstance(s.get("added"), int)) if total_added > 0: st.balloons() st.metric("New Records Added", total_added) # ===== PUSH TAB ===== with tab3: if config.get("is_railway") and config.get("sync_method") == "manual_upload": st.header("⬆️ Upload Data (Manual Sync)") st.info("πŸ“€ **Manual Upload**: Upload database files from your local computer or OneDrive") # File upload functionality st.markdown("### πŸ“€ Upload Database Files") st.markdown("Upload database files from your local computer or OneDrive:") uploaded_files = st.file_uploader( "Choose database files", type=['sqlite', 'zip'], accept_multiple_files=True, help="Upload individual .sqlite files or a ZIP file containing multiple databases" ) if uploaded_files: st.success(f"βœ… {len(uploaded_files)} file(s) selected") for uploaded_file in uploaded_files: st.write(f"πŸ“„ {uploaded_file.name} ({uploaded_file.size / 1024:.1f} KB)") # Process uploaded files if uploaded_file.name.endswith('.zip'): st.info("πŸ“¦ ZIP file detected - will extract individual databases") # TODO: Implement ZIP extraction and database import else: st.info(f"πŸ“„ SQLite file: {uploaded_file.name}") # TODO: Implement database import if st.button("πŸ“₯ Import Database Files", type="primary"): st.success("βœ… Import complete! Database files have been updated.") st.rerun() st.markdown("### πŸ“‹ Instructions") st.markdown(""" 1. **Export** database files from your local GelPredict 2. **Upload** files using the uploader above 3. **Import** into Railway database 4. **Sync** across all your Railway deployments """) elif config.get("is_railway") and config.get("sync_method") not in ["onedrive_api", "manual_upload", "cloud_database"]: st.header("☁️ Cloud Sync Options") st.info("πŸš‚ **Railway Cloud Sync**: Choose a sync method in the Setup tab") st.markdown("**Available options:**") st.markdown("- ☁️ **OneDrive API**: Direct cloud-to-cloud sync") st.markdown("- πŸ“€ **Manual Upload/Download**: Export/import database files") st.markdown("- πŸ—„οΈ **Cloud Database**: Connect to remote database") elif config.get("is_railway") or config.get("sync_method") == "railway_disabled": st.header("🚫 Sync Disabled on Railway") st.warning("πŸš‚ **Railway Limitation**: OneDrive sync is not available on Railway deployments.") st.info(""" **Railway runs on remote servers and cannot access your local OneDrive folders.** **For data sync, use the local version:** 1. Run locally: `streamlit run app/data_entry_gui.py` 2. Use Sync Manager β†’ OneDrive sync 3. Your data will sync across all your computers """) else: st.header("⬆️ Push Data to Remote (Sync Out)") st.caption("Send your local data to remote folder for other computers to access") if config["sync_method"] == "none": st.warning("⚠️ Configure sync method in Setup tab first") else: remote_root = Path(config["sync_folder"]) # Warn if trash if ".Trash" in str(remote_root): st.error("❌ Sync is configured to Trash folder!") st.warning("⚠️ Go to Setup tab and select your actual OneDrive folder") st.info(f"Current (wrong): `{remote_root}`") # Show platform-appropriate example path import os if os.name == 'nt': # Windows example_path = "C:\\Users\\YourName\\OneDrive\\GelPredict_Sync" else: # macOS/Linux example_path = "/Users/ariellewolter/Library/CloudStorage/OneDrive-OldDominionUniversity/GelPredict_Sync" st.info(f"Should be like: `{example_path}`") st.stop() # Create remote if it doesn't exist if not remote_root.exists(): st.warning(f"πŸ“ Sync folder doesn't exist yet: `{remote_root}`") if st.button("πŸ“ Create Remote Folder", type="primary"): try: remote_root.mkdir(parents=True, exist_ok=True) st.success(f"βœ… Created: {remote_root}") st.balloons() except Exception as e: st.error(f"❌ Failed to create: {e}") if remote_root.exists(): st.success(f"βœ… Remote folder exists") st.info(f"πŸ“‚ Syncing to: `{remote_root}`") # Preview st.markdown("### πŸ“Š Preview") for name, local_db in DATABASES.items(): if local_db.exists(): local_size = local_db.stat().st_size / 1024 st.write(f"- {name}: {local_size:.1f} KB ready to push") st.markdown("---") if st.button("πŸ“€ PUSH DATA TO REMOTE", type="primary", use_container_width=True): with st.spinner("Pushing..."): st.info(f"πŸ“ Pushing to: `{remote_root}`") stats = push_to_folder(remote_root, config) config["last_sync"] = datetime.now().isoformat() save_sync_config(config) st.success("βœ… Push complete!") st.success(f"πŸ“ Files copied to: `{remote_root}`") # Show what was actually synced st.markdown("**Synced files:**") for db_name, db_stats in stats.get("databases", {}).items(): if db_stats: st.write(f"- {db_name}: {db_stats}") st.info("πŸ’‘ **Check OneDrive folder** - Files should appear in the subfolder structure") # ===== DELETE TAB ===== with tab4: show_delete_interface() if __name__ == "__main__": st.set_page_config(page_title="Sync Manager", page_icon="πŸ”„", layout="wide") show_sync_app()
"""
GelPredict Multi-Computer Sync Manager
- Conflict-free merge: NEVER overwrites data
- Append-only sync: new records are merged in
- Safe deletes: requires explicit confirmation
- Cloud storage options: Dropbox, Google Drive, OneDrive, Git
- Backup before every sync
- Folder picker for easy setup
"""
from __future__ import annotations
import streamlit as st
import sqlite3
import pandas as pd
import shutil
from pathlib import Path
from datetime import datetime
import hashlib
import json
import subprocess
import platform
import os
ROOT = Path(__file__).resolve().parents[1]
# Sync configuration
SYNC_CONFIG_FILE = ROOT / "sync_config.json"
SYNC_BACKUP_DIR = ROOT / "sync_backups"
SYNC_BACKUP_DIR.mkdir(exist_ok=True)
# All databases to sync
DATABASES = {
"lab_hydrogels": ROOT / "gelpredict.db",
"lit_hydrogels": ROOT / "data" / "reference_db.sqlite",
"lab_cellgrowth": ROOT / "data" / "cellgrowth_lab.sqlite",
"lit_cellgrowth": ROOT / "data" / "cellgrowth_lit.sqlite",
"lab_morphology": ROOT / "data" / "morphology_lab.sqlite",
"lit_morphology": ROOT / "data" / "morphology_literature.sqlite",
}
# Tables to sync (append-only)
SYNC_TABLES = {
"gelpredict.db": ["wells_master_v4", "reagents_per_well", "events_long", "gel_images", "plates_registry"],
"reference_db.sqlite": ["literature_wells", "literature_images"],
"cellgrowth_lab.sqlite": ["cell_runs", "cell_run_hydrogels", "cell_media_components", "cell_events", "cell_images"],
"cellgrowth_lit.sqlite": ["lit_cell_runs", "lit_cell_run_hydrogels", "lit_media_components", "lit_cell_events", "lit_cell_images"],
"morphology_lab.sqlite": ["morphology_observations", "morphology_images", "marker_staining"],
"morphology_literature.sqlite": ["lit_morphology_observations", "lit_morphology_images", "lit_marker_staining"],
}
# ---------------- CSV Export Functions ----------------
def export_database_to_csv(db_path: Path, remote_root: Path) -> dict:
"""Export SQLite database tables to CSV files in the remote sync folder."""
if not db_path.exists():
return {"error": f"Database not found: {db_path}"}
stats = {"exported": 0, "errors": []}
db_name = db_path.stem # e.g., "gelpredict" from "gelpredict.db"
csv_dir = remote_root / f"{db_name}_csv"
csv_dir.mkdir(parents=True, exist_ok=True)
try:
with sqlite3.connect(db_path) as conn:
# Get all table names
cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [row[0] for row in cursor.fetchall()]
for table in tables:
try:
# Export table to CSV
df = pd.read_sql_query(f"SELECT * FROM {table}", conn)
csv_path = csv_dir / f"{table}.csv"
df.to_csv(csv_path, index=False)
stats["exported"] += 1
st.caption(f" πŸ“„ Exported {table}.csv ({len(df)} rows)")
except Exception as e:
stats["errors"].append(f"{table}: {e}")
except Exception as e:
stats["errors"].append(f"Database connection: {e}")
return stats
# ---------------- Sync Configuration ----------------
def load_sync_config() -> dict:
"""Load sync configuration from JSON file."""
# Check if running on Railway (cloud deployment)
is_railway = os.getenv("RAILWAY_ENVIRONMENT") is not None
if SYNC_CONFIG_FILE.exists() and not is_railway:
with open(SYNC_CONFIG_FILE) as f:
return json.load(f)
# Default config - disable sync on Railway
config = {
"sync_method": "none", # 'none' | 'dropbox' | 'gdrive' | 'onedrive' | 'git' | 'network_drive'
"sync_folder": "",
"last_sync": None,
"computer_id": hashlib.md5(str(ROOT).encode()).hexdigest()[:8], # Unique ID for this computer
"is_railway": is_railway,