""" Media Formulation Tracker - Store and manage common media formulations - Save media recipes with components and concentrations - Provide dropdown access for cell growth experiments """ import streamlit as st import sqlite3 import pandas as pd from pathlib import Path from datetime import datetime import json import os try: from shared_parameters import ( BASE_MEDIA, SERA_SUPPLEMENTS, GROWTH_FACTORS, EXTRA_ADDITIONS, ALL_CONCENTRATION_UNITS ) except ImportError: # Fallback constants for cloud deployment BASE_MEDIA = ["DMEM", "RPMI", "MEM", "F12", "Other"] SERA_SUPPLEMENTS = ["FBS", "HS", "CS", "None"] GROWTH_FACTORS = ["EGF", "FGF", "HGF", "TGF-ฮฒ", "None"] EXTRA_ADDITIONS = ["Insulin", "Hydrocortisone", "Cholera Toxin", "None"] ALL_CONCENTRATION_UNITS = ["M", "mM", "ยตM", "nM", "mg/mL", "ยตg/mL", "ng/mL", "%", "x"] # ============================================================================ # DATABASE CONNECTION # ============================================================================ ROOT = Path(__file__).resolve().parents[1] DB_PATH = Path(os.getenv("GELPREDICT_DB", str(ROOT / "gelpredict.db"))).resolve() def get_connection(): con = sqlite3.connect(str(DB_PATH)) con.row_factory = sqlite3.Row con.execute("PRAGMA foreign_keys=ON;") con.execute("PRAGMA journal_mode=WAL;") return con def _connect(): """Consistent connection function following app pattern""" return get_connection() def ensure_media_tracker_schema(): """Ensure the media formulations table exists.""" with get_connection() as con: con.execute(""" CREATE TABLE IF NOT EXISTS media_formulations ( formulation_id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT, components_json TEXT NOT NULL, total_volume_ml REAL DEFAULT 1000.0, created_by TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP, updated_at TEXT DEFAULT CURRENT_TIMESTAMP, is_favorite INTEGER DEFAULT 0 ) """) # Create index for faster lookups con.execute(""" CREATE INDEX IF NOT EXISTS idx_media_formulations_name ON media_formulations(name) """) def save_media_formulation(name, description, components, total_volume=1000.0, created_by="", is_favorite=False): """Save a media formulation to the database.""" formulation_id = f"MED-{datetime.now().strftime('%y%m%d')}-{datetime.now().strftime('%H%M%S')}" with get_connection() as con: con.execute(""" INSERT INTO media_formulations (formulation_id, name, description, components_json, total_volume_ml, created_by, is_favorite) VALUES (?, ?, ?, ?, ?, ?, ?) """, (formulation_id, name, description, json.dumps(components), total_volume, created_by, is_favorite)) con.commit() return formulation_id def get_media_formulations(): """Get all saved media formulations.""" with get_connection() as con: df = pd.read_sql_query(""" SELECT * FROM media_formulations ORDER BY is_favorite DESC, name ASC """, con) return df def delete_media_formulation(formulation_id): """Delete a media formulation.""" with get_connection() as con: con.execute("DELETE FROM media_formulations WHERE formulation_id = ?", (formulation_id,)) con.commit() def update_media_formulation(formulation_id, name, description, components, total_volume=1000.0, is_favorite=False): """Update an existing media formulation.""" with get_connection() as con: con.execute(""" UPDATE media_formulations SET name = ?, description = ?, components_json = ?, total_volume_ml = ?, is_favorite = ?, updated_at = CURRENT_TIMESTAMP WHERE formulation_id = ? """, (name, description, json.dumps(components), total_volume, is_favorite, formulation_id)) con.commit() def get_saved_media_formulations(): """Get saved media formulations for dropdown use.""" try: with get_connection() as con: df = pd.read_sql_query(""" SELECT formulation_id, name, is_favorite FROM media_formulations ORDER BY is_favorite DESC, name ASC """, con) return df except: return pd.DataFrame() # ============================================================================ # UI COMPONENTS # ============================================================================ def show_media_formulation_builder(): """Show the media formulation builder interface.""" st.header("๐Ÿงช Media Formulation Builder") st.caption("Create and save reusable media formulations") # Initialize session state for media components if "media_components" not in st.session_state: st.session_state.media_components = [] # Media builder section st.subheader("๐Ÿ“‹ Build Media Formulation") st.caption("Add components to build your media formulation") col_btn1, col_btn2, col_btn3, col_btn4 = st.columns(4) with col_btn1: if st.button("โž• Base Media", use_container_width=True): st.session_state.show_base_media = True with col_btn2: if st.button("โž• Serum/Supplement", use_container_width=True): st.session_state.show_serum = True with col_btn3: if st.button("โž• Growth Factor", use_container_width=True): st.session_state.show_growth_factor = True with col_btn4: if st.button("โž• Extra Addition", use_container_width=True): st.session_state.show_extra = True # Component forms (same as in cell growth) _show_base_media_form() _show_serum_form() _show_growth_factor_form() _show_extra_form() # Display current formulation if st.session_state.media_components: st.subheader("๐Ÿ“Š Current Formulation") for i, comp in enumerate(st.session_state.media_components): with st.expander(f"Component {i+1}: {comp['name']}", expanded=False): col1, col2, col3 = st.columns(3) with col1: st.write(f"**Name:** {comp['name']}") st.write(f"**Category:** {comp['category']}") with col2: if comp.get('value'): st.write(f"**Concentration:** {comp['value']} {comp.get('units', '')}") else: st.write("**Concentration:** Not specified") with col3: if comp.get('notes'): st.write(f"**Notes:** {comp['notes']}") if st.button("๐Ÿ—‘๏ธ Remove", key=f"remove_comp_{i}"): st.session_state.media_components.pop(i) st.rerun() # Save formulation section if st.session_state.media_components: st.markdown("---") st.subheader("๐Ÿ’พ Save Formulation") col1, col2 = st.columns(2) with col1: formulation_name = st.text_input("Formulation Name*", placeholder="e.g., Standard DMEM + 10% FBS") with col2: total_volume = st.number_input("Total Volume (mL)", value=1000.0, min_value=1.0, step=100.0) description = st.text_area("Description (optional)", placeholder="Brief description of this media formulation...") col1, col2, col3 = st.columns(3) with col1: created_by = st.text_input("Created By", placeholder="Your initials") with col2: is_favorite = st.checkbox("โญ Mark as Favorite", help="Favorites appear at the top of dropdown lists") with col3: if st.button("๐Ÿ’พ Save Formulation", type="primary", use_container_width=True): if formulation_name: try: formulation_id = save_media_formulation( name=formulation_name, description=description, components=st.session_state.media_components, total_volume=total_volume, created_by=created_by, is_favorite=is_favorite ) st.success(f"โœ… Formulation **{formulation_name}** saved!") st.success(f"๐Ÿ“ ID: {formulation_id}") # Clear the form st.session_state.media_components = [] st.rerun() except Exception as e: st.error(f"โŒ Error saving formulation: {e}") else: st.error("โŒ Please enter a formulation name") else: st.info("๐Ÿ‘† Add components above to build a media formulation") def _show_base_media_form(): """Show base media addition form.""" if st.session_state.get("show_base_media"): with st.expander("๐Ÿงช Add Base Media", expanded=True): bm_col1, bm_col2 = st.columns([2,1]) with bm_col1: bm_name = st.selectbox("Base media*", BASE_MEDIA, key="bm_name_builder") with bm_col2: bm_vol = st.number_input("Volume (mL/L)", 0.0, 1000.0, 1000.0, 10.0, key="bm_vol_builder", help="Usually 1000 mL/L for base") bm_notes = st.text_input("Notes (optional)", key="bm_notes_builder") col_add, col_cancel = st.columns(2) with col_add: if st.button("โœ… Add", key="add_base_media_builder", use_container_width=True): st.session_state.media_components.append({ "name": bm_name, "category": "base_media", "value": bm_vol if bm_vol > 0 else None, "units": "mL/L", "notes": bm_notes }) st.session_state.show_base_media = False st.rerun() with col_cancel: if st.button("โŒ Cancel", key="cancel_base_media_builder", use_container_width=True): st.session_state.show_base_media = False st.rerun() def _show_serum_form(): """Show serum/supplement addition form.""" if st.session_state.get("show_serum"): with st.expander("๐Ÿฉธ Add Serum/Supplement", expanded=True): sr_col1, sr_col2, sr_col3 = st.columns(3) with sr_col1: sr_name = st.selectbox("Serum/Supplement*", SERA_SUPPLEMENTS, key="sr_name_builder") with sr_col2: sr_val = st.number_input("Concentration", 0.0, 100.0, 10.0, 0.5, key="sr_val_builder") with sr_col3: sr_units = st.selectbox("Units", ["%", "v/v%", "mL/L"], key="sr_units_builder") sr_notes = st.text_input("Notes (optional)", key="sr_notes_builder") col_add, col_cancel = st.columns(2) with col_add: if st.button("โœ… Add", key="add_serum_builder", use_container_width=True): st.session_state.media_components.append({ "name": sr_name, "category": "serum", "value": sr_val if sr_val > 0 else None, "units": sr_units, "notes": sr_notes }) st.session_state.show_serum = False st.rerun() with col_cancel: if st.button("โŒ Cancel", key="cancel_serum_builder", use_container_width=True): st.session_state.show_serum = False st.rerun() def _show_growth_factor_form(): """Show growth factor addition form.""" if st.session_state.get("show_growth_factor"): with st.expander("๐Ÿงฌ Add Growth Factor", expanded=True): gf_col1, gf_col2, gf_col3 = st.columns(3) with gf_col1: gf_name = st.selectbox("Growth Factor*", GROWTH_FACTORS, key="gf_name_builder") with gf_col2: gf_val = st.number_input("Concentration", 0.0, 1000.0, 10.0, 0.1, key="gf_val_builder") with gf_col3: gf_units = st.selectbox("Units", ["ng/mL", "ฮผg/mL", "ng/ฮผL", "ฮผM", "nM"], key="gf_units_builder") gf_notes = st.text_input("Notes (optional)", key="gf_notes_builder") col_add, col_cancel = st.columns(2) with col_add: if st.button("โœ… Add", key="add_growth_factor_builder", use_container_width=True): st.session_state.media_components.append({ "name": gf_name, "category": "growth_factor", "value": gf_val if gf_val > 0 else None, "units": gf_units, "notes": gf_notes }) st.session_state.show_growth_factor = False st.rerun() with col_cancel: if st.button("โŒ Cancel", key="cancel_growth_factor_builder", use_container_width=True): st.session_state.show_growth_factor = False st.rerun() def _show_extra_form(): """Show extra addition form.""" if st.session_state.get("show_extra"): with st.expander("๐Ÿ”ฌ Add Extra Component", expanded=True): ex_col1, ex_col2, ex_col3 = st.columns(3) with ex_col1: ex_name = st.selectbox("Extra Addition*", EXTRA_ADDITIONS, key="ex_name_builder") with ex_col2: ex_val = st.number_input("Concentration", 0.0, 1000.0, 1.0, 0.1, key="ex_val_builder") with ex_col3: ex_units = st.selectbox("Units", ALL_CONCENTRATION_UNITS, key="ex_units_builder") ex_notes = st.text_input("Notes (optional)", key="ex_notes_builder") col_add, col_cancel = st.columns(2) with col_add: if st.button("โœ… Add", key="add_extra_builder", use_container_width=True): st.session_state.media_components.append({ "name": ex_name, "category": "extra", "value": ex_val if ex_val > 0 else None, "units": ex_units, "notes": ex_notes }) st.session_state.show_extra = False st.rerun() with col_cancel: if st.button("โŒ Cancel", key="cancel_extra_builder", use_container_width=True): st.session_state.show_extra = False st.rerun() def show_media_formulation_library(): """Show the library of saved media formulations.""" st.header("๐Ÿ“š Media Formulation Library") st.caption("Manage your saved media formulations") formulations_df = get_media_formulations() if formulations_df.empty: st.info("No media formulations saved yet. Create one in the **Media Builder** tab.") return st.write(f"**Total Formulations:** {len(formulations_df)}") # Filters with st.expander("๐Ÿ” Filter Formulations", expanded=False): filter_col1, filter_col2 = st.columns(2) with filter_col1: filter_favorites = st.checkbox("Favorites Only") with filter_col2: filter_creator = st.text_input("Created By") # Apply filters filtered_df = formulations_df.copy() if filter_favorites: filtered_df = filtered_df[filtered_df['is_favorite'] == 1] if filter_creator: filtered_df = filtered_df[filtered_df['created_by'].str.contains(filter_creator, case=False, na=False)] if filtered_df.empty: st.warning("No formulations match your filters.") return # Display formulations for idx, row in filtered_df.iterrows(): with st.container(): col1, col2, col3, col4 = st.columns([3, 2, 2, 2]) with col1: favorite_icon = "โญ " if row['is_favorite'] else "" st.write(f"**{favorite_icon}{row['name']}**") if row['description']: st.caption(row['description']) with col2: st.write(f"**Created by:** {row['created_by'] or 'Unknown'}") st.caption(f"**Volume:** {row['total_volume_ml']} mL") with col3: components = json.loads(row['components_json']) st.write(f"**Components:** {len(components)}") st.caption(f"**Created:** {row['created_at'][:10]}") with col4: # Action buttons btn_col1, btn_col2, btn_col3 = st.columns(3) with btn_col1: if st.button("๐Ÿ‘๏ธ", key=f"view_{row['formulation_id']}", help="View details"): st.session_state[f"view_formulation_{row['formulation_id']}"] = True st.rerun() with btn_col2: if st.button("โœ๏ธ", key=f"edit_{row['formulation_id']}", help="Edit"): st.session_state[f"edit_formulation_{row['formulation_id']}"] = True st.rerun() with btn_col3: if st.button("๐Ÿ—‘๏ธ", key=f"delete_{row['formulation_id']}", help="Delete"): st.session_state[f"delete_formulation_{row['formulation_id']}"] = True st.rerun() st.divider() # Handle actions for idx, row in formulations_df.iterrows(): formulation_id = row['formulation_id'] if st.session_state.get(f"view_formulation_{formulation_id}"): st.session_state[f"view_formulation_{formulation_id}"] = False _show_formulation_details(row) return if st.session_state.get(f"edit_formulation_{formulation_id}"): st.session_state[f"edit_formulation_{formulation_id}"] = False _show_edit_formulation_form(row) return if st.session_state.get(f"delete_formulation_{formulation_id}"): st.session_state[f"delete_formulation_{formulation_id}"] = False _show_delete_formulation_confirmation(row) return def _show_formulation_details(row): """Show detailed view of a media formulation.""" st.subheader(f"๐Ÿ“‹ {row['name']}") col1, col2 = st.columns(2) with col1: st.write(f"**Description:** {row['description'] or 'No description'}") st.write(f"**Created by:** {row['created_by'] or 'Unknown'}") st.write(f"**Total Volume:** {row['total_volume_ml']} mL") with col2: st.write(f"**Created:** {row['created_at']}") st.write(f"**Updated:** {row['updated_at']}") st.write(f"**Favorite:** {'โญ Yes' if row['is_favorite'] else 'No'}") st.subheader("๐Ÿงช Components") components = json.loads(row['components_json']) if components: for i, comp in enumerate(components, 1): with st.expander(f"Component {i}: {comp['name']}", expanded=False): col1, col2, col3 = st.columns(3) with col1: st.write(f"**Category:** {comp['category']}") with col2: if comp.get('value'): st.write(f"**Concentration:** {comp['value']} {comp.get('units', '')}") else: st.write("**Concentration:** Not specified") with col3: if comp.get('notes'): st.write(f"**Notes:** {comp['notes']}") else: st.info("No components specified") if st.button("โŒ Close", key=f"close_view_{row['formulation_id']}"): st.rerun() def _show_edit_formulation_form(row): """Show form to edit a media formulation.""" st.subheader(f"โœ๏ธ Edit: {row['name']}") # Pre-populate form col1, col2 = st.columns(2) with col1: name = st.text_input("Formulation Name*", value=row['name'], key=f"edit_name_{row['formulation_id']}") total_volume = st.number_input("Total Volume (mL)", value=float(row['total_volume_ml']), min_value=1.0, step=100.0, key=f"edit_volume_{row['formulation_id']}") with col2: created_by = st.text_input("Created By", value=row['created_by'] or "", key=f"edit_creator_{row['formulation_id']}") is_favorite = st.checkbox("โญ Mark as Favorite", value=bool(row['is_favorite']), key=f"edit_favorite_{row['formulation_id']}") description = st.text_area("Description", value=row['description'] or "", key=f"edit_desc_{row['formulation_id']}") # Show components (read-only for now) st.subheader("๐Ÿงช Components") components = json.loads(row['components_json']) for i, comp in enumerate(components, 1): with st.expander(f"Component {i}: {comp['name']}", expanded=False): col1, col2, col3 = st.columns(3) with col1: st.write(f"**Category:** {comp['category']}") with col2: if comp.get('value'): st.write(f"**Concentration:** {comp['value']} {comp.get('units', '')}") else: st.write("**Concentration:** Not specified") with col3: if comp.get('notes'): st.write(f"**Notes:** {comp['notes']}") # Save/Cancel buttons col1, col2 = st.columns(2) with col1: if st.button("๐Ÿ’พ Save Changes", key=f"save_edit_{row['formulation_id']}", type="primary"): try: update_media_formulation( formulation_id=row['formulation_id'], name=name, description=description, components=components, # Keep existing components for now total_volume=total_volume, is_favorite=is_favorite ) st.success(f"โœ… Formulation **{name}** updated!") st.rerun() except Exception as e: st.error(f"โŒ Error updating formulation: {e}") with col2: if st.button("โŒ Cancel", key=f"cancel_edit_{row['formulation_id']}"): st.rerun() def _show_delete_formulation_confirmation(row): """Show confirmation dialog for deleting a formulation.""" st.subheader(f"๐Ÿ—‘๏ธ Delete: {row['name']}") st.warning("โš ๏ธ **This action cannot be undone!**") st.write("**Formulation to be deleted:**") st.write(f"- **Name:** {row['name']}") st.write(f"- **Created by:** {row['created_by'] or 'Unknown'}") st.write(f"- **Components:** {len(json.loads(row['components_json']))}") st.write(f"- **Created:** {row['created_at']}") col1, col2 = st.columns(2) with col1: if st.button("๐Ÿ—‘๏ธ Delete Permanently", key=f"confirm_delete_{row['formulation_id']}", type="primary"): try: delete_media_formulation(row['formulation_id']) st.success(f"โœ… Formulation **{row['name']}** deleted!") st.rerun() except Exception as e: st.error(f"โŒ Error deleting formulation: {e}") with col2: if st.button("โŒ Cancel", key=f"cancel_delete_{row['formulation_id']}"): st.rerun() # ============================================================================ # MAIN APP # ============================================================================ def show_app(): st.title("๐Ÿงช Media Formulation Tracker") st.caption("Create, save, and manage your media formulations") ensure_media_tracker_schema() tab1, tab2 = st.tabs(["๐Ÿงช Builder", "๐Ÿ“š Library"]) with tab1: show_media_formulation_builder() with tab2: show_media_formulation_library() if __name__ == "__main__": st.set_page_config(page_title="Media Formulation Tracker", page_icon="๐Ÿงช", layout="wide") show_app()