import re import streamlit as st from personas import PROFILE_BLOCKS from profile_io import ( build_settings, dump_settings, load_settings, parse_block, parse_metabolomics, ) REPORT_PROMPT_RE = re.compile( r"\b(meal\s*plan|nutrition\s*plan|exercise|workout|training\s*(plan|routine)|" r"routine|report|regimen|program)\b", re.IGNORECASE, ) def uses_report_pipeline(text: str) -> bool: """Route plan/report generation requests through the RAG pipeline.""" return bool(REPORT_PROMPT_RE.search(text)) def setup(): if "messages" not in st.session_state: st.session_state.messages = [] if "retry_prompt" not in st.session_state: st.session_state.retry_prompt = None if "editor_epoch" not in st.session_state: st.session_state.editor_epoch = 0 if "person_info" not in st.session_state: # Copy so edits never mutate the module-level PROFILE_BLOCKS template. # personas.py uses "person_info"; the editor/save path uses "Basic info" # — normalize so both readers always find their key. blocks = dict(PROFILE_BLOCKS) blocks.setdefault("Basic info", blocks.get("person_info", "")) st.session_state.person_info = blocks def get_person_info_text() -> str: """Flatten the profile-blocks dict into the text passed to the pipelines.""" blocks = st.session_state.person_info basic = blocks.get("Basic info") or blocks.get("person_info", "") return "\n".join( [basic, blocks["Routine & food log"], blocks.get("Metabolomics", "")] ) def render_attr_editor(items, prefix): """Render each attribute as its own labelled field; long values get a text area.""" edited = [] last_section = object() for i, (section, key, val) in enumerate(items): if section != last_section: if section is not None: st.markdown(f"**{section}**") last_section = section field_key = f"{prefix}_{i}" if len(val) > 60 or "\n" in val: new_val = st.text_area(key, value=val, key=field_key) else: new_val = st.text_input(key, value=val, key=field_key) edited.append((section, key, new_val)) return edited def render_profile_browser(): """Sidebar: edit profile fields, biomarkers, and download/load current settings.""" with st.sidebar: blocks = st.session_state.person_info epoch = st.session_state.editor_epoch st.subheader("✏️ Edit Basic Info") basic_items = parse_block(blocks.get("Basic info") or blocks["person_info"]) new_basic = render_attr_editor(basic_items, prefix=f"basic_{epoch}") st.subheader("✏️ Edit Routine & Food Log") routine_items = parse_block(blocks["Routine & food log"]) new_routine = render_attr_editor(routine_items, prefix=f"routine_{epoch}") st.subheader("🧬 Edit Biomarkers") meta_title, meta_df = parse_metabolomics(blocks.get("Metabolomics", "")) new_meta_title = st.text_input( "Profile label", value=meta_title, key=f"metabolomics_title_{epoch}", ) new_meta_df = st.data_editor( meta_df, num_rows="dynamic", use_container_width=True, height=360, hide_index=True, key=f"metabolomics_editor_{epoch}", ) current_blocks = build_settings( new_basic, new_routine, new_meta_title, new_meta_df ) if st.button("Save changes", type="primary", use_container_width=True): st.session_state.person_info = current_blocks st.toast("Profile updated.") st.rerun() st.download_button( "Save current setting", data=dump_settings(current_blocks), file_name="omiver-current-setting.json", mime="application/json", use_container_width=True, help="Download the current profile, routine, and biomarker table.", ) uploaded = st.file_uploader( "Load settings", type=["json"], key=f"settings_upload_{epoch}", ) if uploaded is not None: try: loaded = load_settings(uploaded.getvalue(), existing=blocks) except (ValueError, UnicodeDecodeError, TypeError) as exc: st.error(f"Could not load settings: {exc}") else: st.session_state.person_info = loaded st.session_state.editor_epoch = epoch + 1 st.toast("Settings loaded.") st.rerun() def respond(prompt: str, stream=False): from db_agent import query_rag history = [msg["content"] for msg in st.session_state.messages] return query_rag(history + [prompt], get_person_info_text(), stream=stream) def render_response_error(prompt: str, exc: Exception): reason = str(exc) hint = ( "The configured CHAT_MODEL is not available on this NVIDIA account. " "Set CHAT_MODEL to nvidia/nemotron-3.5-super-vl-120b-a12b in the Space secrets." if "404" in reason or "Not found" in reason else "Please check your inference provider credits/quota." ) error = ( f"⚠️ Sorry, I couldn't generate a response.\n\n" f"**Reason:** `{exc}`\n\n" f"{hint}" ) st.markdown(error) if st.button("Retry response", key="retry_response"): st.session_state.retry_prompt = prompt st.rerun() def render_chat(): st.title("Experiment") for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) if prompt := st.chat_input("Ask anything about this athlete..."): with st.chat_message("user"): st.markdown(prompt) st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("assistant"): response_placeholder = st.empty() with st.spinner("Thinking... analyzing the athlete's profile"): try: response_parts = [] for chunk in respond(prompt, stream=True): response_parts.append(chunk) response_placeholder.markdown("".join(response_parts)) resp = "".join(response_parts) except Exception as exc: st.session_state.retry_prompt = prompt render_response_error(prompt, exc) return st.session_state.messages.append({"role": "assistant", "content": resp}) st.rerun() if st.session_state.retry_prompt: retry_prompt = st.session_state.retry_prompt with st.chat_message("assistant"): response_placeholder = st.empty() with st.spinner("Retrying response..."): try: response_parts = [] for chunk in respond(retry_prompt, stream=True): response_parts.append(chunk) response_placeholder.markdown("".join(response_parts)) resp = "".join(response_parts) except Exception as exc: render_response_error(retry_prompt, exc) return st.session_state.retry_prompt = None st.session_state.messages.append({"role": "assistant", "content": resp}) st.rerun() setup() render_profile_browser() render_chat()