""" Literature ECM Batch Form - Document ECM processing from published papers - All fields optional (papers often incomplete) - Citation parser integration - Unknown checkboxes for unreported parameters """ import streamlit as st import sqlite3 import pandas as pd from datetime import datetime, date from pathlib import Path import json import os import re # Import shared utilities try: from shared_parameters import * except ImportError: # Fallback for cloud deployment import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) from shared_parameters import * try: from citation_parser import parse_citation except ImportError: def parse_citation(text): return {} # ============================================================================ # DATABASE CONNECTION (Reference DB for Literature) # ============================================================================ ROOT = Path(__file__).resolve().parents[1] REF_DB = ROOT / "data" / "reference_db.sqlite" def get_ref_conn(): con = sqlite3.connect(str(REF_DB)) 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_ref_conn() from contextlib import contextmanager @contextmanager def tx_ref(): con = get_ref_conn() try: con.execute("BEGIN IMMEDIATE;") yield con con.execute("COMMIT;") except Exception as e: con.execute("ROLLBACK;") raise e finally: con.close() # ============================================================================ # BATCH ID GENERATION (same as lab) # ============================================================================ def generate_batch_id(family: str, species: str = None, tissue: str = None, date_obj=None, is_commercial: bool = False) -> str: """Auto-generate batch_id.""" if is_commercial: return "" parts = [] family_map = {"decECM": "dECM", "collagen": "COL", "fibrin": "FIB", "alginate": "ALG", "gelMA": "gMA", "gelatin": "GEL", "hyaluronan": "HA", "PEG_DA": "PEG", "composite": "COMP", "other": "OTH"} parts.append(family_map.get(family, family[:4].upper())) if family == "decECM" and species and tissue: species_map = {"human": "Hu", "porcine": "Por", "bovine": "Bov", "rat": "Rat", "mouse": "Mou", "avian": "Avi"} tissue_map = {"mammary": "Mam", "dermis": "Der", "small_intestine_submucosa": "SIS", "myocardium": "Myo", "liver": "Liv", "lung": "Lun"} sp = species_map.get(species, species[:3].title()) ts = tissue_map.get(tissue, tissue[:3].title()) parts.append(f"{sp}{ts}") if date_obj: dt = datetime.fromisoformat(date_obj) if isinstance(date_obj, str) else date_obj parts.append(dt.strftime("%y%m%d")) else: parts.append(datetime.now().strftime("%y%m%d")) return "-".join(parts) # ============================================================================ # UI # ============================================================================ def show_lit_batch_form(codebook): """Literature ECM Batch form.""" st.header("📚 Document Literature ECM Batch") st.caption("Document ECM processing from published papers") st.info("💡 All fields optional - papers often don't report complete processing details. Use Unknown checkboxes liberally!") # Initialize session state if "lit_batch_proc_steps" not in st.session_state: st.session_state.lit_batch_proc_steps = [] # Initialize step counter for unique IDs if "lit_step_counter" not in st.session_state: st.session_state.lit_step_counter = 0 # ========== CITATION PARSER ========== st.markdown("### 🔍 Citation") citation_input = st.text_area( "Paste Full Citation", placeholder="Smith J et al. (2023). Decellularized mammary ECM. Biomaterials. DOI: 10.1016/...", height=100 ) if st.button("🔍 Parse Citation"): if citation_input: parsed = parse_citation(citation_input) st.session_state["lit_batch_parsed"] = parsed st.success("✅ Citation parsed!") parsed = st.session_state.get("lit_batch_parsed", {}) # ========== PUBLICATION INFO ========== st.markdown("**📄 Publication Details**") p1, p2, p3 = st.columns(3) with p1: first_author = st.text_input("First Author", value=parsed.get("first_author", "")) publication_year = st.number_input("Year", 1950, 2030, parsed.get("publication_year") or 2023) with p2: paper_title = st.text_input("Paper Title", value=parsed.get("paper_title", "")) source_label = st.text_input("Source Label", value=parsed.get("source_label", ""), placeholder="Smith 2023") with p3: doi = st.text_input("DOI", value=parsed.get("doi", "")) citation = st.text_area("Full Citation", value=parsed.get("citation", "") or citation_input, height=50) st.markdown("---") # ========== BATCH IDENTITY ========== st.subheader("đŸ§Ŧ ECM Identity") # Commercial product checkbox is_commercial = st.checkbox( "🏭 Commercial Product", value=False, help="Check if paper used commercial ECM (Matrigel, Cultrex, etc.)" ) if is_commercial: st.markdown("**đŸˇī¸ Commercial Product Details**") COMMERCIAL_PRODUCTS = { "Matrigel": {"vendor": "Corning", "family": "composite"}, "Matrigel GFR": {"vendor": "Corning", "family": "composite"}, "Cultrex": {"vendor": "R&D Systems", "family": "collagen"}, "Cultrex BME": {"vendor": "R&D Systems", "family": "composite"}, "Geltrex": {"vendor": "Thermo Fisher", "family": "composite"}, "PureCol": {"vendor": "Advanced BioMatrix", "family": "collagen"}, "VitroCol": {"vendor": "Advanced BioMatrix", "family": "collagen"}, "Rat Tail Collagen I": {"vendor": "Corning", "family": "collagen"}, "Bovine Collagen I": {"vendor": "Sigma-Aldrich", "family": "collagen"}, "Porcine Collagen I": {"vendor": "Sigma-Aldrich", "family": "collagen"}, "Collagen I (Human)": {"vendor": "Corning", "family": "collagen"}, "Type I Collagen": {"vendor": "Various", "family": "collagen"}, "Gelatin (Porcine)": {"vendor": "Sigma-Aldrich", "family": "gelatin"}, "Gelatin (Bovine)": {"vendor": "Sigma-Aldrich", "family": "gelatin"}, "Gelatin (Fish)": {"vendor": "Sigma-Aldrich", "family": "gelatin"}, "Custom/Other": {"vendor": "", "family": ""} } c1, c2 = st.columns(2) with c1: product_name = st.selectbox("Product Name*", [""] + list(COMMERCIAL_PRODUCTS.keys())) if product_name and product_name != "Custom/Other": vendor = COMMERCIAL_PRODUCTS[product_name]["vendor"] family_hint = COMMERCIAL_PRODUCTS[product_name]["family"] else: vendor = st.text_input("Vendor Name") family_hint = None with c2: if product_name == "Custom/Other": custom_product = st.text_input("Custom Product Name") else: custom_product = None catalog_num = st.text_input("Catalog Number") website = st.text_input("Company Website", placeholder="https://www.corning.com", help="Company website URL") lot_num = st.text_input("Lot Number", help="If reported in paper (often not provided)") st.caption("💡 Papers often only mention product name, not lot number") else: product_name = vendor = catalog_num = lot_num = custom_product = website = family_hint = None m1, m2, m3 = st.columns(3) with m1: if is_commercial and family_hint: family = st.selectbox("ECM Family*", [""] + codebook['family'], index=codebook['family'].index(family_hint)+1 if family_hint in codebook['family'] else 0, help="Auto-filled from product selection") else: family = st.selectbox("ECM Family*", [""] + codebook['family']) with m2: label_species = "Species (optional)" if is_commercial else "Species" dec_species = st.selectbox(label_species, [""] + codebook['species'], help="Optional for commercial (often not disclosed)") with m3: label_tissue = "Tissue (optional)" if is_commercial else "Tissue" dec_tissue = st.selectbox(label_tissue, [""] + codebook['tissues'], help="Optional for commercial (often not disclosed)") collagen_type = st.text_input("Collagen Type", placeholder="Type I, Type II, etc.") st.markdown("---") # ========== ECM CHARACTERIZATION ========== st.subheader("📊 ECM Characterization") st.caption("💡 Papers often don't report these - use Unknown checkboxes") with st.expander("Characterization Measurements (if reported)", expanded=False): char1, char2, char3 = st.columns(3) with char1: unk_protein = st.checkbox("Unknown", key="lit_batch_unk_protein", help="Unknown/not measured") ecm_total_protein_mgml = st.number_input("Protein (mg/mL)", 0.0, 100.0, 0.0, 0.1, disabled=unk_protein, key="lit_batch_protein_conc") if unk_protein: ecm_total_protein_mgml = None protein_assay_method = st.selectbox("Assay Method", ["","BCA","Bradford","Lowry","DC_assay","A280","other"], disabled=unk_protein, key="lit_batch_protein_assay") with char2: unk_ph = st.checkbox("Unknown", key="lit_batch_unk_ph", help="Unknown/not measured") pre_pH = st.number_input("Pre-pH", 0.0, 14.0, 0.0, 0.1, disabled=unk_ph, help="pH before neutralization", key="lit_batch_pre_ph") if unk_ph: pre_pH = None unk_cond = st.checkbox("Unknown", key="lit_batch_unk_cond", help="Unknown/not measured") pre_conductivity_mS = st.number_input("Pre-Conductivity (mS/cm)", 0.0, 100.0, 0.0, 0.1, disabled=unk_cond, key="lit_batch_pre_cond") if unk_cond: pre_conductivity_mS = None with char3: unk_uv = st.checkbox("Unknown", key="lit_batch_unk_uv", help="Unknown/not measured") uv_A220 = st.number_input("UV A220", 0.0, 1e6, 0.0, 0.01, disabled=unk_uv, key="lit_batch_uv_a220") uv_A280 = st.number_input("UV A280", 0.0, 1e6, 0.0, 0.01, disabled=unk_uv, key="lit_batch_uv_a280") if unk_uv: uv_A220 = None uv_A280 = None # Auto-calculate UV ratio uv_ratio = None if uv_A220 and uv_A280 and uv_A220 > 0 and uv_A280 > 0: uv_ratio = uv_A220 / uv_A280 st.info(f"📊 UV ratio A220/A280: **{uv_ratio:.3f}**") # Generate batch ID if is_commercial: if lot_num: batch_id = f"{product_name or 'Commercial'}-{lot_num}" else: # No lot number - use product name + author + year author_short = first_author[:4].upper() if first_author else "UNK" batch_id = f"{product_name or 'Commercial'}-{author_short}{publication_year % 100}" st.success(f"✅ Batch ID: **{batch_id}**") elif family: batch_id = generate_batch_id(family, dec_species, dec_tissue, date.today()) st.success(f"✅ Batch ID: **{batch_id}** (for reference)") else: batch_id = "" st.markdown("---") # ========== PRE-STORAGE ========== st.subheader("🧊 Pre-Processing Tissue Storage") st.caption("âš ī¸ Often not reported in papers - use Unknown checkboxes") with st.expander("Pre-Storage (if reported)", expanded=False): ps1, ps2 = st.columns(2) with ps1: pre_storage_temp = st.selectbox("Storage temp (°C)", ["", "4°C (fridge)", "-20°C (freezer)", "-80°C (ultra-freezer)", "-196°C (LN2)", "Other"], help="Temperature at which tissue was stored before processing", key="lit_batch_storage_temp") if pre_storage_temp == "Other": pre_storage_temp_custom = st.number_input("Custom temp (°C)", -200.0, 50.0, 0.0, 1.0, key="lit_batch_storage_temp_custom") else: pre_storage_temp_custom = None with ps2: unk_frozen = st.checkbox("Unknown", key="lit_unk_frozen") pre_storage_duration_months = st.number_input("Frozen (months)", 0.0, 120.0, 0.0, 0.5, disabled=unk_frozen) if unk_frozen: pre_storage_duration_months = None st.markdown("---") # ========== ECM PROCESSING PROTOCOL ========== st.subheader("đŸ”Ŧ ECM Processing Protocol") st.caption("Document what the paper reports - use Unknown for missing parameters") # Comprehensive protocol builder (matching lab version) st.caption("**Add Processing Steps:**") row1 = st.columns(6) step_types = [ ("Decell", "decell"), ("Wash", "wash"), ("Delipid", "delipid"), ("Enzyme", "enzyme"), ("Homogenize", "homogenize"), ("Grind", "grind") ] for i, (label, stype) in enumerate(step_types): with row1[i]: if st.button(f"➕ {label}", key=f"add_{stype}_litbatch"): st.session_state.lit_step_counter += 1 st.session_state.lit_batch_proc_steps.append({ "type": stype, "id": st.session_state.lit_step_counter }) st.rerun() row2 = st.columns(6) step_types2 = [ ("Freeze-Thaw", "freeze_thaw"), ("Lyophilize", "lyophilize"), ("Reconstitute", "reconstitute"), ("pH Adjust", "ph_adjust"), ("Dialysis", "dialysis"), ("Filtration", "filtration") ] for i, (label, stype) in enumerate(step_types2): with row2[i]: if st.button(f"➕ {label}", key=f"add_{stype}_litbatch"): st.session_state.lit_step_counter += 1 st.session_state.lit_batch_proc_steps.append({ "type": stype, "id": st.session_state.lit_step_counter }) st.rerun() row3 = st.columns(6) with row3[0]: if st.button("➕ Centrifuge", key="add_centrifuge_litbatch"): st.session_state.lit_step_counter += 1 st.session_state.lit_batch_proc_steps.append({ "type": "centrifuge", "id": st.session_state.lit_step_counter }) st.rerun() with row3[1]: if st.button("➕ Storage", key="add_storage_litbatch"): st.session_state.lit_step_counter += 1 st.session_state.lit_batch_proc_steps.append({ "type": "storage", "id": st.session_state.lit_step_counter }) st.rerun() with row3[2]: if st.button("➕ Other", key="add_other_litbatch"): st.session_state.lit_step_counter += 1 st.session_state.lit_batch_proc_steps.append({ "type": "other", "id": st.session_state.lit_step_counter }) st.rerun() if st.button("đŸ—‘ī¸ Clear All", key="clear_litbatch_steps"): st.session_state.lit_batch_proc_steps = [] st.rerun() if st.session_state.lit_batch_proc_steps: st.caption(f"**{len(st.session_state.lit_batch_proc_steps)} step(s) added**") # Display steps with detailed parameters (matching lab version) processing_steps = [] for i, step in enumerate(st.session_state.lit_batch_proc_steps): with st.expander(f"Step {i+1}: {step['type'].title()}", expanded=True): if step["type"] == "reconstitute": st.caption("💡 Critical: Enter lyoph weight + recon volume to calculate stock concentration") recol1, recol2, recol3, recol4 = st.columns(4) with recol1: solvent_sel = st.selectbox("Solvent", ["PBS", "DI water", "0.5M acetic acid", "Other"], key=f"recon_solv_lit_{step['id']}") if solvent_sel == "Other": solvent = st.text_input("Specify", key=f"recon_solv_other_lit_{step['id']}") else: solvent = solvent_sel with recol2: unk_wt = st.checkbox("Unk", key=f"unk_recon_wt_lit_{step['id']}") lyoph_wt = st.number_input("Lyoph weight (mg)", 0.0, 10000.0, 100.0, 1.0, disabled=unk_wt, key=f"recon_wt_lit_{step['id']}") if unk_wt: lyoph_wt = None with recol3: unk_vol = st.checkbox("Unk", key=f"unk_recon_vol_lit_{step['id']}") recon_vol = st.number_input("Recon volume (mL)", 0.0, 1000.0, 10.0, 0.1, disabled=unk_vol, key=f"recon_vol_lit_{step['id']}") if unk_vol: recon_vol = None with recol4: unk_temp = st.checkbox("Unk", key=f"unk_recon_temp_lit_{step['id']}") recon_temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, disabled=unk_temp, key=f"recon_temp_lit_{step['id']}") if unk_temp: recon_temp = None # Auto-calculate concentration final_conc = None if lyoph_wt and recon_vol and lyoph_wt > 0 and recon_vol > 0: final_conc = lyoph_wt / recon_vol st.success(f"✅ **Stock concentration: {final_conc:.2f} mg/mL**") notes = st.text_input("Notes", placeholder="e.g., with pepsin 0.1 mg/mL, stirred overnight", key=f"recon_notes_lit_{step['id']}") processing_steps.append({ "type": "reconstitute", "solvent": solvent, "lyoph_weight_mg": lyoph_wt, "recon_volume_mL": recon_vol, "final_conc_mgml": final_conc, "temp_C": recon_temp, "notes": notes or None }) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "decell": st.caption("💡 Decellularization: Remove cells while preserving ECM structure") dcol1, dcol2, dcol3, dcol4 = st.columns(4) with dcol1: from app.shared_parameters import DECELL_AGENTS reagent_sel = st.selectbox("Reagent", DECELL_AGENTS, key=f"decell_reag_sel_lit_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify reagent", placeholder="e.g., custom detergent", key=f"decell_reag_other_lit_{step['id']}") else: reagent = reagent_sel with dcol2: unk_conc = st.checkbox("Unk", key=f"unk_decell_conc_lit_{step['id']}") conc_val = st.number_input("Concentration", 0.0, 100.0, 1.0, 0.1, disabled=unk_conc, key=f"decell_conc_lit_{step['id']}") conc_unit = st.selectbox("Units", ["%","M","mM","mg/mL","v/v"], disabled=unk_conc, key=f"decell_unit_lit_{step['id']}") if unk_conc: conc_val, conc_unit = None, None with dcol3: unk_dur = st.checkbox("Unk", key=f"unk_decell_dur_lit_{step['id']}") duration = st.number_input("Duration (hours)", 0.0, 1000.0, 24.0, 0.5, disabled=unk_dur, key=f"decell_dur_lit_{step['id']}") if unk_dur: duration = None unk_temp = st.checkbox("Unk", key=f"unk_decell_temp_lit_{step['id']}") temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, disabled=unk_temp, key=f"decell_temp_lit_{step['id']}") if unk_temp: temp = None with dcol4: unk_chg = st.checkbox("Unk", key=f"unk_decell_chg_lit_{step['id']}") changes = st.number_input("# Changes", 1, 100, 3, 1, disabled=unk_chg, key=f"decell_chg_lit_{step['id']}") if unk_chg: changes = None notes = st.text_input("Notes", placeholder="e.g., gentle agitation, sterile conditions", key=f"decell_notes_lit_{step['id']}") processing_steps.append({ "type": "decell", "reagent": reagent, "concentration": conc_val, "conc_units": conc_unit, "duration_hours": duration, "temp_C": temp, "changes": changes, "notes": notes or None }) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "wash": st.caption("💡 Washing: Remove residual reagents and cellular debris") wcol1, wcol2, wcol3, wcol4 = st.columns(4) with wcol1: solution_sel = st.selectbox("Solution", ["PBS", "DI water", "0.9% NaCl", "Tris buffer", "Other"], key=f"wash_sol_sel_lit_{step['id']}") if solution_sel == "Other": solution = st.text_input("Specify solution", placeholder="e.g., custom buffer", key=f"wash_sol_other_lit_{step['id']}") else: solution = solution_sel with wcol2: unk_conc = st.checkbox("Unk", key=f"unk_wash_conc_lit_{step['id']}") conc_val = st.number_input("Conc", 0.0, 100.0, 1.0, 0.1, disabled=unk_conc, key=f"wash_conc_lit_{step['id']}") conc_unit = st.selectbox("Units", ["x","M","mM","%","n/a"], disabled=unk_conc, key=f"wash_unit_lit_{step['id']}") if unk_conc: conc_val, conc_unit = None, None with wcol3: unk_washes = st.checkbox("Unk", key=f"unk_wash_num_lit_{step['id']}") washes = st.number_input("# Washes", 1, 20, 3, 1, disabled=unk_washes, key=f"wash_num_lit_{step['id']}") if unk_washes: washes = None unk_dur = st.checkbox("Unk", key=f"unk_wash_dur_lit_{step['id']}") duration = st.number_input("Duration each (min)", 0.0, 500.0, 15.0, 5.0, disabled=unk_dur, key=f"wash_dur_lit_{step['id']}") if unk_dur: duration = None with wcol4: unk_temp = st.checkbox("Unk", key=f"unk_wash_temp_lit_{step['id']}") temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, disabled=unk_temp, key=f"wash_temp_lit_{step['id']}") if unk_temp: temp = None notes = st.text_input("Notes", placeholder="e.g., gentle shaking, sterile conditions", key=f"wash_notes_lit_{step['id']}") processing_steps.append({ "type": "wash", "solution": solution, "concentration": conc_val, "conc_units": conc_unit, "n_washes": washes, "duration_min": duration, "temp_C": temp, "notes": notes or None }) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "delipid": from app.shared_parameters import DELIPID_SOLVENTS dlcol1, dlcol2, dlcol3, dlcol4 = st.columns(4) with dlcol1: solvent_sel = st.selectbox("Solvent", DELIPID_SOLVENTS, key=f"delip_solv_sel_lit_{step['id']}") if solvent_sel == "Other": solvent = st.text_input("Specify solvent", placeholder="e.g., custom solvent", key=f"delip_solv_other_lit_{step['id']}") else: solvent = solvent_sel with dlcol2: conc_val = st.number_input("Concentration", 0.0, 100.0, 100.0, 1.0, key=f"delip_conc_lit_{step['id']}") conc_unit = st.selectbox("Units", ["%","v/v"], key=f"delip_unit_lit_{step['id']}") with dlcol3: duration = st.number_input("Duration (hours)", 0.0, 100.0, 2.0, 0.25, key=f"delip_dur_lit_{step['id']}") temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"delip_temp_lit_{step['id']}", help="Room temp, fridge, etc.") with dlcol4: times = st.number_input("# Times", 1, 20, 3, 1, key=f"delip_times_lit_{step['id']}", help="Number of repetitions") notes = st.text_input("Notes (optional)", placeholder="e.g., vortex, solvent grade", key=f"delip_notes_lit_{step['id']}") processing_steps.append({"type": "delipid", "solvent": solvent, "concentration": conc_val, "conc_units": conc_unit, "duration_hours": duration, "temp_C": temp, "n_times": times, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "enzyme": from app.shared_parameters import COMMON_ENZYMES ecol1, ecol2, ecol3, ecol4 = st.columns(4) with ecol1: enzyme_sel = st.selectbox("Enzyme", COMMON_ENZYMES, key=f"enz_name_sel_lit_{step['id']}") if enzyme_sel == "Other": enzyme = st.text_input("Specify enzyme", placeholder="e.g., custom enzyme", key=f"enz_name_other_lit_{step['id']}") else: enzyme = enzyme_sel with ecol2: conc = st.number_input("Conc.", 0.0, 100.0, 1.0, 0.1, key=f"enz_conc_lit_{step['id']}") units = st.selectbox("Units", ["mg/mL", "U/mL", "mg/g"], key=f"enz_units_lit_{step['id']}") with ecol3: duration = st.number_input("Duration (hours)", 0.0, 500.0, 48.0, 1.0, key=f"enz_dur_lit_{step['id']}") with ecol4: temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"enz_temp_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., pH maintained, shaking speed", key=f"enz_notes_lit_{step['id']}") processing_steps.append({"type": "enzyme", "enzyme": enzyme, "concentration": conc, "conc_units": units, "duration_hours": duration, "temp_C": temp, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "homogenize": from app.shared_parameters import COMMON_BUFFERS, COMMON_DILUENTS hcol1, hcol2, hcol3, hcol4 = st.columns(4) with hcol1: medium = st.selectbox("Medium/Liquid", COMMON_BUFFERS + COMMON_DILUENTS + ["PBS", "Saline", "DI water", "Other"], key=f"homog_medium_lit_{step['id']}") if medium == "Other": medium = st.text_input("Specify medium", placeholder="e.g., 0.1M HCl", key=f"homog_medium_other_lit_{step['id']}") with hcol2: rpm = st.number_input("RPM", 0, 50000, 10000, 1000, key=f"homog_rpm_lit_{step['id']}") duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"homog_dur_lit_{step['id']}") with hcol3: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"homog_temp_lit_{step['id']}") passes = st.number_input("# Passes", 1, 20, 1, 1, key=f"homog_passes_lit_{step['id']}") with hcol4: volume = st.number_input("Volume (mL)", 0.0, 1000.0, 10.0, 1.0, key=f"homog_vol_lit_{step['id']}") ratio = st.text_input("Tissue:Medium ratio", placeholder="e.g., 1:10, 1:20", key=f"homog_ratio_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., sterile conditions, ice bath", key=f"homog_notes_lit_{step['id']}") processing_steps.append({"type": "homogenize", "medium": medium, "rpm": rpm, "duration_min": duration, "temp_C": temp, "passes": passes, "volume_mL": volume, "tissue_medium_ratio": ratio, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "grind": gcol1, gcol2, gcol3, gcol4 = st.columns(4) with gcol1: method = st.selectbox("Method", ["mortar_pestle", "ball_mill", "cryomill", "other"], key=f"grind_method_lit_{step['id']}") if method == "other": method = st.text_input("Specify method", key=f"grind_method_other_lit_{step['id']}") with gcol2: duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"grind_dur_lit_{step['id']}") with gcol3: temp = st.number_input("Temp (°C)", -200.0, 50.0, 4.0, 1.0, key=f"grind_temp_lit_{step['id']}") with gcol4: cycles = st.number_input("# Cycles", 1, 50, 1, 1, key=f"grind_cycles_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, sterile", key=f"grind_notes_lit_{step['id']}") processing_steps.append({"type": "grind", "method": method, "duration_min": duration, "temp_C": temp, "cycles": cycles, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "freeze_thaw": ftcol1, ftcol2, ftcol3, ftcol4 = st.columns(4) with ftcol1: cycles = st.number_input("# Cycles", 1, 50, 3, 1, key=f"ft_cycles_lit_{step['id']}") with ftcol2: freeze_temp = st.number_input("Freeze temp (°C)", -200.0, 0.0, -80.0, 10.0, key=f"ft_ftemp_lit_{step['id']}") with ftcol3: thaw_temp = st.number_input("Thaw temp (°C)", 0.0, 50.0, 37.0, 1.0, key=f"ft_ttemp_lit_{step['id']}") with ftcol4: duration_cycle = st.number_input("Duration/cycle (min)", 0.0, 1000.0, 60.0, 5.0, key=f"ft_dur_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, water bath", key=f"ft_notes_lit_{step['id']}") processing_steps.append({"type": "freeze_thaw", "cycles": cycles, "freeze_temp_C": freeze_temp, "thaw_temp_C": thaw_temp, "duration_min": duration_cycle, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "lyophilize": lycol1, lycol2, lycol3, lycol4 = st.columns(4) with lycol1: unk_lyoph_dur = st.checkbox("Unk", key=f"unk_lyoph_dur_lit_{step['id']}", help="Unknown/not reported") duration = st.number_input("Duration (hours)", 0.0, 200.0, 48.0, 1.0, disabled=unk_lyoph_dur, key=f"lyoph_dur_lit_{step['id']}") if unk_lyoph_dur: duration = None with lycol2: temp = st.number_input("Temp (°C)", -100.0, 0.0, -50.0, 5.0, key=f"lyoph_temp_lit_{step['id']}") with lycol3: unk_press = st.checkbox("Unk", key=f"unk_lyoph_press_lit_{step['id']}", help="Unknown/not reported") pressure = st.number_input("Pressure (mTorr)", 0.0, 1000.0, 100.0, 10.0, disabled=unk_press, key=f"lyoph_press_lit_{step['id']}") if unk_press: pressure = None with lycol4: notes = st.text_input("Notes (optional)", placeholder="e.g., ramp rate, condenser temp", key=f"lyoph_notes_lit_{step['id']}") processing_steps.append({"type": "lyophilize", "duration_hours": duration, "temp_C": temp, "pressure_mTorr": pressure, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "ph_adjust": from app.shared_parameters import COMMON_BASES, COMMON_ACIDS phcol1, phcol2, phcol3, phcol4 = st.columns(4) with phcol1: direction = st.radio("Direction", ["Raise pH (base)", "Lower pH (acid)"], key=f"ph_dir_lit_{step['id']}", horizontal=True) if "base" in direction: reagent_sel = st.selectbox("Base", COMMON_BASES + ["Other"], key=f"ph_base_sel_lit_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify base", placeholder="e.g., custom base", key=f"ph_base_other_lit_{step['id']}") else: reagent = reagent_sel else: reagent_sel = st.selectbox("Acid", COMMON_ACIDS + ["Other"], key=f"ph_acid_sel_lit_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify acid", placeholder="e.g., custom acid", key=f"ph_acid_other_lit_{step['id']}") else: reagent = reagent_sel with phcol2: conc = st.number_input("Concentration", 0.0, 10.0, 0.1, 0.01, key=f"ph_conc_lit_{step['id']}") units = st.selectbox("Units", ["M", "mM", "%"], key=f"ph_units_lit_{step['id']}") with phcol3: target_ph = st.number_input("Target pH", 1.0, 14.0, 7.4, 0.1, key=f"ph_target_lit_{step['id']}") duration = st.number_input("Duration (min)", 0.0, 500.0, 30.0, 1.0, key=f"ph_dur_lit_{step['id']}") with phcol4: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"ph_temp_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., dropwise addition, stirring", key=f"ph_notes_lit_{step['id']}") processing_steps.append({"type": "ph_adjust", "reagent": reagent, "concentration": conc, "conc_units": units, "target_ph": target_ph, "duration_min": duration, "temp_C": temp, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "dialysis": from app.shared_parameters import COMMON_BUFFERS, COMMON_ACIDS dcol1, dcol2, dcol3, dcol4 = st.columns(4) with dcol1: buffer_sel = st.selectbox("Buffer/Solution", COMMON_BUFFERS + COMMON_ACIDS, key=f"dial_buf_sel_lit_{step['id']}") if buffer_sel == "Other": buffer = st.text_input("Specify buffer", placeholder="e.g., custom buffer", key=f"dial_buf_other_lit_{step['id']}") else: buffer = buffer_sel with dcol2: conc_val = st.number_input("Concentration", 0.0, 10.0, 1.0, 0.1, key=f"dial_conc_lit_{step['id']}") conc_unit = st.selectbox("Units", ["M", "mM", "%"], key=f"dial_unit_lit_{step['id']}") with dcol3: changes = st.number_input("# Buffer changes", 1, 20, 3, 1, key=f"dial_changes_lit_{step['id']}") duration = st.number_input("Duration (hours)", 0.0, 500.0, 24.0, 1.0, key=f"dial_dur_lit_{step['id']}") with dcol4: temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"dial_temp_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., MWCO 3.5kDa, stirring, volume ratio 1:100", key=f"dial_notes_lit_{step['id']}") processing_steps.append({"type": "dialysis", "buffer": buffer, "concentration": conc_val, "conc_units": conc_unit, "n_changes": changes, "duration_hours": duration, "temp_C": temp, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "storage": scol1, scol2, scol3, scol4 = st.columns(4) with scol1: temp = st.number_input("Temp (°C)", -200.0, 50.0, -80.0, 1.0, key=f"stor_temp_lit_{step['id']}") with scol2: duration = st.text_input("Duration", placeholder="e.g., 7 days, 3 months", key=f"stor_dur_lit_{step['id']}") with scol3: container = st.selectbox("Container", ["tube", "vial", "bag", "plate", "other"], key=f"stor_container_lit_{step['id']}") with scol4: atmosphere = st.selectbox("Atmosphere", ["air", "nitrogen", "vacuum", "argon"], key=f"stor_atmo_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., sterile, labeled", key=f"stor_notes_lit_{step['id']}") processing_steps.append({"type": "storage", "temp_C": temp, "duration": duration, "container": container, "atmosphere": atmosphere, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "filtration": fcol1, fcol2, fcol3, fcol4 = st.columns(4) with fcol1: filter_type = st.selectbox("Filter type", ["spin_filter", "syringe_filter", "vacuum_filter", "gravity_filter", "other"], key=f"filt_type_lit_{step['id']}") with fcol2: pore_size = st.number_input("Pore size (Îŧm)", 0.0, 100.0, 0.22, 0.01, key=f"filt_pore_lit_{step['id']}") rpm = st.number_input("RPM", 0, 50000, 3000, 500, key=f"filt_rpm_lit_{step['id']}") with fcol3: duration_min = st.number_input("Duration (min)", 0.0, 500.0, 10.0, 1.0, key=f"filt_dur_lit_{step['id']}") with fcol4: temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"filt_temp_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., filter brand, pre-wet, flow rate", key=f"filt_notes_lit_{step['id']}") processing_steps.append({"type": "filtration", "filter_type": filter_type, "pore_size": pore_size, "rpm": rpm, "duration_min": duration_min, "temp_C": temp, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "centrifuge": ccol1, ccol2, ccol3, ccol4 = st.columns(4) with ccol1: purpose = st.selectbox("Purpose", ["clarification", "concentration", "pellet_removal", "debris_removal", "other"], key=f"cent_purp_lit_{step['id']}") if purpose == "other": purpose = st.text_input("Specify purpose", key=f"cent_purp_other_lit_{step['id']}") with ccol2: speed = st.number_input("Speed (RCF)", 0, 50000, 3000, 100, key=f"cent_speed_lit_{step['id']}") duration = st.number_input("Duration (min)", 0.0, 300.0, 10.0, 1.0, key=f"cent_dur_lit_{step['id']}") with ccol3: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"cent_temp_lit_{step['id']}") cycles = st.number_input("# Cycles", 1, 10, 1, 1, key=f"cent_cycles_lit_{step['id']}") with ccol4: volume = st.number_input("Volume (mL)", 0.0, 1000.0, 50.0, 5.0, key=f"cent_vol_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., rotor type, brake settings", key=f"cent_notes_lit_{step['id']}") processing_steps.append({"type": "centrifuge", "purpose": purpose, "speed_rcf": speed, "duration_min": duration, "temp_C": temp, "cycles": cycles, "volume_mL": volume, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "additive": from app.shared_parameters import COMMON_BUFFERS, COMMON_BASES, COMMON_SALTS acol1, acol2, acol3, acol4 = st.columns(4) with acol1: reagent_sel = st.selectbox("Reagent", COMMON_BUFFERS + COMMON_BASES + COMMON_SALTS + ["Other"], key=f"add_reag_sel_lit_{step['id']}") if reagent_sel == "Other": reagent = st.text_input("Specify reagent", placeholder="e.g., custom reagent", key=f"add_reag_other_lit_{step['id']}") else: reagent = reagent_sel with acol2: conc = st.number_input("Concentration", 0.0, 100.0, 1.0, 0.1, key=f"add_conc_lit_{step['id']}") units = st.selectbox("Units", ["M", "mM", "%", "mg/mL"], key=f"add_units_lit_{step['id']}") with acol3: volume = st.number_input("Volume (mL)", 0.0, 1000.0, 1.0, 0.1, key=f"add_vol_lit_{step['id']}") temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"add_temp_lit_{step['id']}") with acol4: notes = st.text_input("Notes (optional)", placeholder="e.g., pH adjustment, preservative", key=f"add_notes_lit_{step['id']}") processing_steps.append({"type": "additive", "reagent": reagent, "concentration": conc, "conc_units": units, "volume_mL": volume, "temp_C": temp, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() elif step["type"] == "other": ocol1, ocol2, ocol3 = st.columns(3) with ocol1: step_name = st.text_input("Step name", placeholder="e.g., sonication", key=f"other_name_lit_{step['id']}") with ocol2: duration = st.number_input("Duration (min)", 0.0, 500.0, 10.0, 1.0, key=f"other_dur_lit_{step['id']}") with ocol3: temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"other_temp_lit_{step['id']}") notes = st.text_input("Notes (optional)", placeholder="e.g., power settings, frequency", key=f"other_notes_lit_{step['id']}") processing_steps.append({"type": "other", "step_name": step_name, "duration_min": duration, "temp_C": temp, "notes": notes or None}) # Remove button for this specific step if st.button("đŸ—‘ī¸ Remove", key=f"remove_step_lit_{step['id']}_{i}"): st.session_state.lit_batch_proc_steps.pop(i) st.rerun() st.markdown("---") # ========== BATCH CHARACTERIZATION ========== st.subheader("📊 Batch Characterization") st.caption("ECM properties (if reported in paper)") with st.expander("Characterization (optional)", expanded=False): c1, c2, c3 = st.columns(3) with c1: unk_protein = st.checkbox("Unknown", key="lit_unk_protein") ecm_total_protein_mgml = st.number_input("Protein (mg/mL)", 0.0, 100.0, 0.0, 0.1, disabled=unk_protein) if unk_protein: ecm_total_protein_mgml = None with c2: unk_ph = st.checkbox("Unknown", key="lit_unk_ph") pre_pH = st.number_input("Pre-pH", 0.0, 14.0, 0.0, 0.1, disabled=unk_ph) if unk_ph: pre_pH = None with c3: unk_cond = st.checkbox("Unknown", key="lit_unk_cond") pre_conductivity_mS = st.number_input("Conductivity (mS/cm)", 0.0, 100.0, 0.0, 0.1, disabled=unk_cond) if unk_cond: pre_conductivity_mS = None st.markdown("---") # ========== NOTES ========== notes_ecm_processing = st.text_area( "📝 ECM Processing Notes", placeholder="Additional details from paper about ECM preparation", height=100 ) st.markdown("---") # ========== SAVE BUTTON ========== if st.button("💾 Save Literature Batch", type="primary", use_container_width=True): # Minimal validation (family optional for commercial) if not is_commercial and not family: st.error("❌ ECM Family required (or check Commercial Product)") return # Create payload payload = { 'batch_id': batch_id or f"LIT-{family}-{datetime.now().strftime('%y%m%d-%H%M')}", 'source_label': source_label or None, 'first_author': first_author or None, 'publication_year': publication_year, 'paper_title': paper_title or None, 'doi': doi or None, 'citation': citation or None, 'material_family': family, 'is_decem': 1 if family == 'decECM' else 0, 'is_commercial_product': int(is_commercial) if is_commercial else 0, 'commercial_vendor': vendor if is_commercial else None, 'commercial_product_name': (custom_product or product_name) if is_commercial else None, 'commercial_catalog_number': catalog_num if is_commercial else None, 'commercial_lot_number': lot_num if is_commercial else None, 'commercial_website': website if is_commercial else None, 'ecm_origin_species': dec_species or None, 'ecm_source_tissue': dec_tissue or None, 'collagen_type': collagen_type or None, 'pre_storage_days_4C': None, # No longer tracking days, only temperature and months 'pre_storage_duration_months': pre_storage_duration_months, 'processing_protocol': json.dumps(processing_steps) if processing_steps else None, 'ecm_total_protein_mgml': ecm_total_protein_mgml if ecm_total_protein_mgml and ecm_total_protein_mgml > 0 else None, 'protein_assay_method': protein_assay_method or None, 'pre_pH': pre_pH if pre_pH and pre_pH > 0 else None, 'pre_conductivity_mS': pre_conductivity_mS if pre_conductivity_mS and pre_conductivity_mS > 0 else None, 'uv_A220': uv_A220 if uv_A220 and uv_A220 > 0 else None, 'uv_A280': uv_A280 if uv_A280 and uv_A280 > 0 else None, 'uv_ratio_A220_A280': uv_ratio if uv_ratio and uv_ratio > 0 else None, 'gel_binary': 0, # Default to no gel for batch creation (gelation results added later) 'notes': notes_ecm_processing or None, 'created_at': datetime.now().isoformat() } try: # Save to literature_wells table cols = list(payload.keys()) vals = [payload[c] for c in cols] with tx_ref() as con: con.execute( f"INSERT INTO literature_wells ({','.join(cols)}) VALUES ({','.join(['?']*len(vals))})", vals ) st.success(f"✅ **Literature Batch Saved!**") st.success(f"đŸ“Ļ Batch ID: **{payload['batch_id']}**") st.info("âžĄī¸ Go to **Literature Gelation** to document gelation conditions from the paper") # Auto-update/generate literature review entry try: from literature_integration import process_literature_entry entry_data = { "first_author": first_author, "publication_year": publication_year, "paper_title": paper_title, "citation": citation, "family": family } result = process_literature_entry(doi or "", "hydrogel", entry_data) if result["tracker_updated"]: st.info(f"📚 {result['message']}") elif result["tracker_generated"]: st.info(f"📚 {result['message']}") elif result["doi_processed"] and not result["tracker_updated"] and not result["tracker_generated"]: st.caption(f"â„šī¸ {result['message']}") except ImportError: st.caption("â„šī¸ Literature review integration not available") except Exception as e: st.caption(f"â„šī¸ Literature review integration error: {e}") # Clear form st.session_state.lit_batch_proc_steps = [] if "lit_batch_parsed" in st.session_state: del st.session_state["lit_batch_parsed"] st.balloons() except Exception as e: st.error(f"❌ Error saving: {e}") # ============================================================================ # MAIN # ============================================================================ def main(): st.set_page_config(page_title="Literature ECM Batch", page_icon="📚", layout="wide") # Load codebook codebook = { 'family': ["collagen", "decECM", "fibrin", "alginate", "gelMA", "gelatin", "hyaluronan", "PEG_DA", "composite", "other"], 'species': ["human", "porcine", "bovine", "rat", "mouse", "avian", "other"], 'tissues': ["mammary", "dermis", "small_intestine_submucosa", "myocardium", "pericardium", "liver", "lung", "kidney", "bladder", "tendon", "cartilage", "meniscus", "adipose", "placenta", "amniotic_membrane", "esophagus", "cornea", "other"] } show_lit_batch_form(codebook) if __name__ == "__main__": main()