Spaces:
Sleeping
Sleeping
Commit ·
1195fbd
1
Parent(s): 3ef1ec4
Add sidebar: move wordmark, model controls, and reset out of main layout
Browse files1105 unmodified lines11061107110811091110111116 unmodified lines11281129113011311132113311341135113611371138113932 unmodified lines1172117311741175117611771178151 unmodified lines133013311332133313341335133619 unmodified lines1356135713581359136013611362136313641365136613671368136913701371137213731374137513761377128 unmodified lines1506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647339 unmodified lines198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201751 unmodified lines20692070207120722073207420752 unmodified lines2078207920802081208220832084208520862087208820892090209120922093209420951105 unmodified lines# Same theme as the desktop app and catllm.com (theme.py).inject_css()# Initialize session stateif 'categories' not in st.session_state:st.session_state.categories = [''] * MAX_CATEGORIES16 unmodified linesif 'extraction_params' not in st.session_state:st.session_state.extraction_params = None # Stores params when categories are auto-extracted# Wordmark: cat-shield mark + IBM Plex Sans "CatLLM" + mono subtitle.render_wordmark("NLP for survey research · UC Berkeley")# About sectionwith st.expander("About This App"):st.markdown("""**Privacy Notice:** Your data is sent to third-party LLM APIs for classification. Do not upload sensitive, confidential, or personally identifiable information (PII).---32 unmodified lines```""")# Main layoutcol_input, col_output = st.columns([1, 1])with col_input:151 unmodified linesif auto_mode:st.session_state.task_mode = "auto_extract"# Auto-extract settingsif st.session_state.task_mode == "auto_extract":st.markdown("### Auto-extract Categories")st.markdown("We'll analyze your data to discover the main categories.")19 unmodified lineshelp="Guide the model to prioritize extracting categories related to this focus")# Model selection for extractionst.markdown("### Model Selection")model_tier = st.radio("Model Tier",options=["Free Models", "Bring Your Own Key"],key="extract_model_tier")if model_tier == "Free Models":model_display = st.selectbox("Model", options=FREE_MODEL_DISPLAY_NAMES, key="extract_model")model = FREE_MODELS_MAP[model_display] # Convert to actual model nameapi_key = ""else:model = st.selectbox("Model", options=PAID_MODEL_CHOICES, key="extract_model_paid")api_key = st.text_input("API Key", type="password", key="extract_api_key")if st.button("Extract Categories", type="primary"):if input_data is None:st.error("Please upload data first")128 unmodified linesst.session_state.category_count += 1st.rerun()st.markdown("### Model Selection")# Classification mode selectorclassify_mode = st.radio("Classification Mode",options=["Single Model", "Model Comparison", "Ensemble"],horizontal=True,key="classify_mode",help="Single: one model. Comparison: see results from multiple models side-by-side. Ensemble: multiple models vote for consensus.")model_tier = st.radio("Model Tier",options=["Free Models", "Bring Your Own Key"],key="classify_model_tier")# Multi-model mode uses multiselectis_multi_model = classify_mode in ["Model Comparison", "Ensemble"]min_models = 3 if classify_mode == "Ensemble" else 2# Track per-run temperatures: list of (model_name, temperature) for ensemble,# or dict {model_name: temperature} for model comparisonmodel_temperatures = {}# ensemble_runs stores list of (model_name, temperature) allowing duplicate modelsensemble_runs = []if classify_mode == "Ensemble":# Ensemble mode: dynamic rows allowing same model multiple times with different tempsif "ensemble_num_runs" not in st.session_state:st.session_state.ensemble_num_runs = 3if model_tier == "Free Models":model_options = FREE_MODEL_DISPLAY_NAMESis_free = Trueelse:model_options = PAID_MODEL_CHOICESis_free = Falsest.markdown(f"**Model Runs** (select {min_models}+ runs)")for i in range(st.session_state.ensemble_num_runs):cols = st.columns([3, 1, 0.5])with cols[0]:default_idx = 0 if i < len(model_options) else i % len(model_options)selected = st.selectbox(f"Run {i+1}", options=model_options,index=default_idx, key=f"ensemble_model_{i}",label_visibility="collapsed")with cols[1]:temp = st.number_input("Temp", min_value=0.0, max_value=2.0, value=round(i * 0.25, 2),step=0.25, key=f"ensemble_temp_{i}", label_visibility="collapsed")with cols[2]:if st.session_state.ensemble_num_runs > 3:if st.button("✕", key=f"ensemble_remove_{i}"):st.session_state.ensemble_num_runs -= 1st.rerun()model_name = FREE_MODELS_MAP[selected] if is_free else selectedensemble_runs.append((model_name, temp))if st.button("Add Run", key="add_ensemble_run"):st.session_state.ensemble_num_runs += 1st.rerun()models_list = [r[0] for r in ensemble_runs]model_temperatures = {f"{r[0]}__run{i}": r[1] for i, r in enumerate(ensemble_runs)}api_key = "" if model_tier == "Free Models" else st.text_input("API Key", type="password", key="classify_api_key")elif is_multi_model:# Model Comparison mode: multiselect (each model unique) + temperature rowif model_tier == "Free Models":default_models = FREE_MODEL_DISPLAY_NAMES[:min_models] if len(FREE_MODEL_DISPLAY_NAMES) >= min_models else FREE_MODEL_DISPLAY_NAMESmodel_displays = st.multiselect(f"Models (select {min_models}+)",options=FREE_MODEL_DISPLAY_NAMES,default=default_models,key="classify_models_multi")models_list = [FREE_MODELS_MAP[d] for d in model_displays]api_key = ""else:default_models = PAID_MODEL_CHOICES[:min_models] if len(PAID_MODEL_CHOICES) >= min_models else PAID_MODEL_CHOICESmodels_list = st.multiselect(f"Models (select {min_models}+)",options=PAID_MODEL_CHOICES,default=default_models,key="classify_models_multi_paid")api_key = st.text_input("API Key", type="password", key="classify_api_key")if models_list:st.markdown("**Model Temperature**")temp_cols = st.columns(len(models_list))for idx, (col, m) in enumerate(zip(temp_cols, models_list)):short_name = m.split('/')[-1].split(':')[0][:20]model_temperatures[m] = col.number_input(short_name,min_value=0.0,max_value=2.0,value=0.0,step=0.25,key=f"temp_{idx}",help=f"Temperature for {m} (0 = deterministic, higher = more creative)")else:# Single model modeif model_tier == "Free Models":model_display = st.selectbox("Model", options=FREE_MODEL_DISPLAY_NAMES, key="classify_model")model = FREE_MODELS_MAP[model_display] # Convert to actual model namemodels_list = [model]api_key = ""else:model = st.selectbox("Model", options=PAID_MODEL_CHOICES, key="classify_model_paid")models_list = [model]api_key = st.text_input("API Key", type="password", key="classify_api_key")# Ensemble-specific optionsconsensus_threshold = 0.5 # Defaultif classify_mode == "Ensemble":consensus_options = {"Majority (50%+)": 0.5,"Two-Thirds (67%+)": 0.67,"Unanimous (100%)": 1.0,}consensus_choice = st.radio("Consensus Rule",options=list(consensus_options.keys()),horizontal=True,key="consensus_choice",help="How many models must agree for a category to be marked present")consensus_threshold = consensus_options[consensus_choice]if st.button("Categorize Data", type="primary", use_container_width=True):if input_data is None:st.error("Please upload data first")339 unmodified linesmime="application/pdf")# Codewith st.expander("See the Code"):st.code(results['code'], language='python')else:st.info("Upload data, select categories, and click 'Categorize Data' to see results here.")# Bottom buttonscol_reset, col_code = st.columns(2)with col_reset:if st.button("Reset", type="secondary", use_container_width=True):st.session_state.categories = [''] * MAX_CATEGORIESst.session_state.category_count = INITIAL_CATEGORIESst.session_state.task_mode = Nonest.session_state.extracted_categories = Nonest.session_state.extraction_params = Nonest.session_state.results = Noneif hasattr(st.session_state, 'example_loaded'):del st.session_state.example_loadedst.rerun()with col_code:if st.button("See in Code", use_container_width=True):st.session_state.show_code_modal = True# Code modal/dialogif st.session_state.get('show_code_modal'):st.markdown("---")st.markdown("### Reproducibility Code")51 unmodified linesif current_categories:# Check if categories were auto-extractedif st.session_state.extraction_params:current_temperatures = results.get('model_temperatures', {})classify_params = {'model': current_model,'description': current_description,2 unmodified lines'models_list': current_models_list,'consensus_threshold': current_consensus,'model_temperatures': current_temperatures,'ensemble_runs': results.get('ensemble_runs'),}code_to_show = generate_full_code(st.session_state.extraction_params, classify_params)else:current_temperatures = results.get('model_temperatures', {})code_to_show = generate_classify_code(current_input_type, current_description, current_categories,current_model, current_model_source, current_mode,classify_mode=current_classify_mode, models_list=current_models_list,consensus_threshold=current_consensus,model_temperatures=current_temperatures,ensemble_runs=results.get('ensemble_runs'),)else:code_to_show = '''import catllm1105 unmodified lines1106110711081109111011111112111311141115111611171118111916 unmodified lines113611371138113911401141114211431144114511461147114811491150115132 unmodified lines11841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383151 unmodified lines153515361537153815391540154119 unmodified lines156115621563156415651566128 unmodified lines169516961697169816991700339 unmodified lines204020412042204320442045204620472048204920502051205251 unmodified lines21042105210621072108210921102 unmodified lines2113211421152116211721182119212021212122212321242125212621272128212921301105 unmodified lines# Same theme as the desktop app and catllm.com (theme.py).inject_css()# Sidebar width CSSst.markdown("""<style>[data-testid="stSidebar"] { min-width: 300px !important; max-width: 300px !important; }</style>""",unsafe_allow_html=True,)# Initialize session stateif 'categories' not in st.session_state:st.session_state.categories = [''] * MAX_CATEGORIES16 unmodified linesif 'extraction_params' not in st.session_state:st.session_state.extraction_params = None # Stores params when categories are auto-extracted# -----------------------------------------------------------------------# SIDEBAR# -----------------------------------------------------------------------with st.sidebar:# Wordmark: cat-shield mark + IBM Plex Sans "CatLLM" + mono subtitle.render_wordmark("NLP for survey research · UC Berkeley")# About sectionwith st.expander("About This App"):st.markdown("""**Privacy Notice:** Your data is sent to third-party LLM APIs for classification. Do not upload sensitive, confidential, or personally identifiable information (PII).---32 unmodified lines```""")st.markdown("---")# ------------------------------------------------------------------# Classification Mode — only shown when task_mode == "manual"# ------------------------------------------------------------------if st.session_state.task_mode == "manual":classify_mode = st.radio("Classification Mode",options=["Single Model", "Model Comparison", "Ensemble"],horizontal=False,key="classify_mode",help="Single: one model. Comparison: see results from multiple models side-by-side. Ensemble: multiple models vote for consensus.")else:# Default value when not in manual mode (auto-extract always uses single model)classify_mode = "Single Model"# ------------------------------------------------------------------# Model Tier# ------------------------------------------------------------------if st.session_state.task_mode == "auto_extract":model_tier = st.radio("Model Tier",options=["Free Models", "Bring Your Own Key"],key="extract_model_tier")else:model_tier = st.radio("Model Tier",options=["Free Models", "Bring Your Own Key"],key="classify_model_tier")# ------------------------------------------------------------------# Model selection — varies by classify_mode# ------------------------------------------------------------------is_multi_model = classify_mode in ["Model Comparison", "Ensemble"]min_models = 3 if classify_mode == "Ensemble" else 2# Track per-run temperaturesmodel_temperatures = {}ensemble_runs = []if st.session_state.task_mode == "auto_extract":# Auto-extract: always single modelif model_tier == "Free Models":model_display = st.selectbox("Model", options=FREE_MODEL_DISPLAY_NAMES, key="extract_model")model = FREE_MODELS_MAP[model_display]api_key = ""else:model = st.selectbox("Model", options=PAID_MODEL_CHOICES, key="extract_model_paid")api_key = st.text_input("API Key", type="password", key="extract_api_key")models_list = [model]elif classify_mode == "Ensemble":# Ensemble mode: dynamic rows allowing same model multiple times with different tempsif "ensemble_num_runs" not in st.session_state:st.session_state.ensemble_num_runs = 3if model_tier == "Free Models":model_options = FREE_MODEL_DISPLAY_NAMESis_free = Trueelse:model_options = PAID_MODEL_CHOICESis_free = Falsest.markdown(f"**Model Runs** (select {min_models}+ runs)")for i in range(st.session_state.ensemble_num_runs):cols = st.columns([3, 1, 0.5])with cols[0]:default_idx = 0 if i < len(model_options) else i % len(model_options)selected = st.selectbox(f"Run {i+1}", options=model_options,index=default_idx, key=f"ensemble_model_{i}",label_visibility="collapsed")with cols[1]:temp = st.number_input("Temp", min_value=0.0, max_value=2.0, value=round(i * 0.25, 2),step=0.25, key=f"ensemble_temp_{i}", label_visibility="collapsed")with cols[2]:if st.session_state.ensemble_num_runs > 3:if st.button("✕", key=f"ensemble_remove_{i}"):st.session_state.ensemble_num_runs -= 1st.rerun()model_name = FREE_MODELS_MAP[selected] if is_free else selectedensemble_runs.append((model_name, temp))if st.button("Add Run", key="add_ensemble_run"):st.session_state.ensemble_num_runs += 1st.rerun()models_list = [r[0] for r in ensemble_runs]model_temperatures = {f"{r[0]}__run{i}": r[1] for i, r in enumerate(ensemble_runs)}model = models_list[0] if models_list else ""api_key = "" if model_tier == "Free Models" else st.text_input("API Key", type="password", key="classify_api_key")elif is_multi_model:# Model Comparison mode: multiselect (each model unique) + temperature rowif model_tier == "Free Models":default_models = FREE_MODEL_DISPLAY_NAMES[:min_models] if len(FREE_MODEL_DISPLAY_NAMES) >= min_models else FREE_MODEL_DISPLAY_NAMESmodel_displays = st.multiselect(f"Models (select {min_models}+)",options=FREE_MODEL_DISPLAY_NAMES,default=default_models,key="classify_models_multi")models_list = [FREE_MODELS_MAP[d] for d in model_displays]api_key = ""else:default_models = PAID_MODEL_CHOICES[:min_models] if len(PAID_MODEL_CHOICES) >= min_models else PAID_MODEL_CHOICESmodels_list = st.multiselect(f"Models (select {min_models}+)",options=PAID_MODEL_CHOICES,default=default_models,key="classify_models_multi_paid")api_key = st.text_input("API Key", type="password", key="classify_api_key")if models_list:st.markdown("**Model Temperature**")temp_cols = st.columns(len(models_list))for idx, (col, m) in enumerate(zip(temp_cols, models_list)):short_name = m.split('/')[-1].split(':')[0][:20]model_temperatures[m] = col.number_input(short_name,min_value=0.0,max_value=2.0,value=0.0,step=0.25,key=f"temp_{idx}",help=f"Temperature for {m} (0 = deterministic, higher = more creative)")model = models_list[0] if models_list else ""else:# Single model modeif model_tier == "Free Models":model_display = st.selectbox("Model", options=FREE_MODEL_DISPLAY_NAMES, key="classify_model")model = FREE_MODELS_MAP[model_display]models_list = [model]api_key = ""else:model = st.selectbox("Model", options=PAID_MODEL_CHOICES, key="classify_model_paid")models_list = [model]api_key = st.text_input("API Key", type="password", key="classify_api_key")# ------------------------------------------------------------------# Ensemble consensus rule# ------------------------------------------------------------------consensus_threshold = 0.5 # Defaultif classify_mode == "Ensemble":consensus_options = {"Majority (50%+)": 0.5,"Two-Thirds (67%+)": 0.67,"Unanimous (100%)": 1.0,}consensus_choice = st.radio("Consensus Rule",options=list(consensus_options.keys()),horizontal=False,key="consensus_choice",help="How many models must agree for a category to be marked present")consensus_threshold = consensus_options[consensus_choice]st.markdown("---")# ------------------------------------------------------------------# "See in Code" button — visible only when results exist# ------------------------------------------------------------------if st.session_state.results:if st.button("See in Code", use_container_width=True):st.session_state.show_code_modal = True# ------------------------------------------------------------------# Reset button at bottom of sidebar# ------------------------------------------------------------------if st.button("Reset", type="secondary", use_container_width=True):st.session_state.categories = [''] * MAX_CATEGORIESst.session_state.category_count = INITIAL_CATEGORIESst.session_state.task_mode = Nonest.session_state.extracted_categories = Nonest.session_state.extraction_params = Nonest.session_state.results = Noneif hasattr(st.session_state, 'example_loaded'):del st.session_state.example_loadedst.rerun()# -----------------------------------------------------------------------# MAIN AREA — 2-column layout# -----------------------------------------------------------------------col_input, col_output = st.columns([1, 1])with col_input:151 unmodified linesif auto_mode:st.session_state.task_mode = "auto_extract"# Auto-extract settings (data settings stay in col_input; model selection is in sidebar)if st.session_state.task_mode == "auto_extract":st.markdown("### Auto-extract Categories")st.markdown("We'll analyze your data to discover the main categories.")19 unmodified lineshelp="Guide the model to prioritize extracting categories related to this focus")if st.button("Extract Categories", type="primary"):if input_data is None:st.error("Please upload data first")128 unmodified linesst.session_state.category_count += 1st.rerun()if st.button("Categorize Data", type="primary", use_container_width=True):if input_data is None:st.error("Please upload data first")339 unmodified linesmime="application/pdf")# Code inline expander (always available in results panel)with st.expander("See the Code"):st.code(results['code'], language='python')else:st.info("Upload data, select categories, and click 'Categorize Data' to see results here.")# Code modal/dialog (triggered from sidebar "See in Code" button)if st.session_state.get('show_code_modal'):st.markdown("---")st.markdown("### Reproducibility Code")51 unmodified linesif current_categories:# Check if categories were auto-extractedif st.session_state.extraction_params:current_temperatures = results.get('model_temperatures', {}) if st.session_state.results else {}classify_params = {'model': current_model,'description': current_description,2 unmodified lines'models_list': current_models_list,'consensus_threshold': current_consensus,'model_temperatures': current_temperatures,'ensemble_runs': st.session_state.results.get('ensemble_runs') if st.session_state.results else None,}code_to_show = generate_full_code(st.session_state.extraction_params, classify_params)else:current_temperatures = st.session_state.results.get('model_temperatures', {}) if st.session_state.results else {}code_to_show = generate_classify_code(current_input_type, current_description, current_categories,current_model, current_model_source, current_mode,classify_mode=current_classify_mode, models_list=current_models_list,consensus_threshold=current_consensus,model_temperatures=current_temperatures,ensemble_runs=st.session_state.results.get('ensemble_runs') if st.session_state.results else None,)else:code_to_show = '''import catllm
app.py+218-183