import ast import json import re from typing import Dict, Set, Tuple, Optional import pandas as pd import time # try to import AgGrid for interactive tables; fallback to native renderers if missing try: from st_aggrid import AgGrid, GridOptionsBuilder HAS_AGGRID = True except Exception: HAS_AGGRID = False import streamlit as st # ========================================== # Logic Functions (Preserved) # ========================================== def build_value_to_getter_map(source: str) -> Tuple[Dict[str, str], Dict[str, Dict[str, str]], Dict[str, str]]: """Parse EnvironmentConfig in CommonEnv_Final.py and return: - value_to_getter: literal -> getter string - env_to_active: env name -> {activeKey: literal} - key_to_getter: activeKey -> function name """ tree = ast.parse(source) value_to_getter: Dict[str, str] = {} class EnvVisitor(ast.NodeVisitor): def __init__(self): self.common_key_to_value: Dict[str, str] = {} self.active_key_to_values: Dict[str, Set[str]] = {} self.env_to_active: Dict[str, Dict[str, str]] = {} self.key_to_getter: Dict[str, str] = {} def visit_ClassDef(self, node: ast.ClassDef): if node.name != "EnvironmentConfig": return # collect dictionaries and activeEnv per env block for item in node.body: if isinstance(item, ast.Assign): for tgt in item.targets: if isinstance(tgt, ast.Name) and tgt.id == "Common_Variables": if isinstance(item.value, ast.Dict): for k, v in zip(item.value.keys, item.value.values): if isinstance(k, ast.Constant) and isinstance(v, ast.Constant): self.common_key_to_value[k.value] = v.value elif isinstance(item, ast.If): # traverse the if / elif / else chain to grab activeEnv blocks for each branch current = item while isinstance(current, ast.If): # gather env names from a simple comparison like: if env == "dev": env_names = [] test = current.test if isinstance(test, ast.Compare) and isinstance(test.left, ast.Name): for comp in test.comparators: if isinstance(comp, ast.Constant) and isinstance(comp.value, str): env_names.append(comp.value) if not env_names: env_names = ["unknown"] # collect activeEnv dict inside this branch (if present) for sub in current.body: if isinstance(sub, ast.Assign): for tgt in sub.targets: if isinstance(tgt, ast.Name) and tgt.id == "activeEnv" and isinstance(sub.value, ast.Dict): for k, v in zip(sub.value.keys, sub.value.values): if isinstance(k, ast.Constant) and isinstance(v, ast.Constant): self.active_key_to_values.setdefault(k.value, set()).add(v.value) for env_name in env_names: self.env_to_active.setdefault(env_name, {})[k.value] = v.value # follow elif chain if present (ast.If in orelse) if current.orelse and len(current.orelse) == 1 and isinstance(current.orelse[0], ast.If): current = current.orelse[0] else: break # read getter functions for item in node.body: if isinstance(item, ast.FunctionDef): if not item.body: continue ret_stmt = item.body[0] if not isinstance(ret_stmt, ast.Return): continue value = ret_stmt.value if isinstance(value, ast.Subscript) and isinstance(value.value, ast.Attribute): container_attr = value.value.attr key_name = None key_node = value.slice if isinstance(key_node, ast.Constant): key_name = key_node.value elif hasattr(ast, 'Index') and isinstance(key_node, ast.Index) and isinstance(key_node.value, ast.Constant): key_name = key_node.value.value if key_name is None: continue if container_attr == 'Common_Variables' and key_name in self.common_key_to_value: literal = self.common_key_to_value[key_name] value_to_getter[literal] = f"EnvironmentConfig.{item.name}()" elif container_attr == 'activeEnv' and key_name in self.active_key_to_values: # record getter name for the activeEnv key and map all found literals self.key_to_getter[key_name] = item.name for literal in self.active_key_to_values[key_name]: value_to_getter[literal] = f"EnvironmentConfig.{item.name}()" visitor = EnvVisitor() visitor.visit(tree) return value_to_getter, visitor.env_to_active, visitor.key_to_getter def parameterize_script(script: str, value_to_getter: Dict[str, str], as_fstring: bool = True) -> str: # Replace literals with getter text. Sort by length to prefer longer matches. sorted_items = sorted(value_to_getter.items(), key=lambda x: -len(x[0])) for literal, getter in sorted_items: pattern = r"\b" + re.escape(literal) + r"\b" replacement = f"{{{getter}}}" if as_fstring else getter script = re.sub(pattern, replacement, script) return script def format_env_prefix(chosen_env: str, env_map: Dict[str, str], key_to_getter: Dict[str, str]) -> str: # Build a header with readable environment parameter references (prefer getter names if available) lines = [f"-- Environment: {chosen_env}"] for k, v in env_map.items(): getter_fn = key_to_getter.get(k) if getter_fn: lines.append(f"-- {getter_fn}() -> {v}") else: lines.append(f"-- {k} -> {v}") return "\n".join(lines) # ========================================== # UI & Styling # ========================================== st.set_page_config( page_title="CommonEnv Parameterizer", page_icon="⚡", layout="wide", initial_sidebar_state="expanded" ) # Custom CSS for Premium Look st.markdown( """ """, unsafe_allow_html=True ) # Sidebar with st.sidebar: st.title("⚡ Dynamic Params") st.markdown("Transform your hardcoded scripts into dynamic, environment-aware code instantly.") st.markdown("---") st.subheader("⚙️ Settings") as_fstring = st.checkbox("Use f-strings `{...}`", value=True, help="Wrap replacements in curly braces for Python f-strings.") # Theme selector theme_choice = st.selectbox("Theme", options=["Colorful Light", "Colorful Dark"], index=0, help="Choose application theme") # persist theme choice in session_state for access elsewhere st.session_state['theme_choice'] = theme_choice # Expose whether AgGrid is available if not HAS_AGGRID: st.caption("Tip: install 'streamlit-aggrid' to get interactive tables in mapping/debug views (optional)") # Apply theme overrides (dark) when chosen if st.session_state.get('theme_choice') == 'Colorful Dark': # if user selected dark theme, inject dark palette overrides st.markdown( """ """, unsafe_allow_html=True, ) st.markdown("---") st.subheader("📖 Help") st.info( """ 1. **Upload** your `CommonEnv_Final.py`. 2. **Select** the target environment. 3. **Paste** your code or table names. 4. **Copy** the parameterized result. """ ) # Main Content st.markdown("# CommonEnv Parameterizer") st.markdown("### Live Preview & Conversion Tool") st.markdown("
", unsafe_allow_html=True) # Step 1: Upload st.markdown('
1
Upload Configuration
', unsafe_allow_html=True) # Provide two ways to input: file upload OR paste config upload_method = st.radio("Choose input method:", ["Upload File", "Paste Config"], horizontal=True) env_src = None if upload_method == "Upload File": env_file = st.file_uploader("Upload CommonEnv master file (.py)", type=["py"], label_visibility="collapsed") if env_file: try: env_src = env_file.read().decode('utf-8') except Exception: try: env_src = env_file.read().decode('latin-1') except Exception as e: st.error(f"❌ Failed to read file: {str(e)}") st.stop() else: st.info("👆 Please upload your `CommonEnv_Final.py` to get started.") st.stop() else: st.markdown("**Paste your CommonEnv configuration below:**") env_src = st.text_area("Paste CommonEnv Python code", height=300, label_visibility="collapsed") if not env_src or env_src.strip() == "": st.info("👈 Please paste your CommonEnv configuration to get started.") st.stop() # Process File if not env_src: st.stop() try: value_to_getter, env_to_active, key_to_getter = build_value_to_getter_map(env_src) except Exception as e: st.error(f"❌ Error parsing configuration: {str(e)}") st.stop() if not value_to_getter: st.error("❌ No mappings detected. Please check your file format.") st.stop() # Success Metrics cols = st.columns(3) with cols[0]: st.markdown( f"""
{len(value_to_getter)}
Mappings Found
""", unsafe_allow_html=True ) with cols[1]: st.markdown( f"""
{len(env_to_active)}
Environments
""", unsafe_allow_html=True ) with cols[2]: st.markdown( f"""
{len(key_to_getter)}
Active Keys
""", unsafe_allow_html=True ) # if AgGrid isn't available, let the user know if not HAS_AGGRID: st.warning("Optional package 'streamlit-aggrid' not installed — tables will render using native Streamlit. For interactive tables install: pip install streamlit-aggrid") st.markdown("
", unsafe_allow_html=True) # Step 2: Workspace st.markdown('
2
Parameterize Code
', unsafe_allow_html=True) col_controls_1, col_controls_2 = st.columns([1, 2]) with col_controls_1: env_options = sorted(list(env_to_active.keys())) if env_to_active else [] chosen_env = st.selectbox("Target Environment", options=env_options, index=0 if env_options else None) if not env_options: st.info("No environment-specific blocks were detected in the uploaded file — Section 3 will be empty until activeEnv blocks are found.") with col_controls_2: example_choice = st.selectbox( "Load Example", options=["— Custom Input —", "examples/sample_schema.sql", "examples/sample_btq.btq"], index=0, ) # Input/Output Area col_in, col_out = st.columns(2) # Hidden trigger input used by JS to indicate a Ctrl+Enter was pressed if '__ctrl_trigger' not in st.session_state: st.session_state['__ctrl_trigger'] = '' if '__last_ctrl_ts' not in st.session_state: st.session_state['__last_ctrl_ts'] = '' if '__last_hint_ts' not in st.session_state: st.session_state['__last_hint_ts'] = '' if 'final_output' not in st.session_state: st.session_state['final_output'] = '' with col_in: st.markdown("
", unsafe_allow_html=True) st.markdown("**Input Code**", unsafe_allow_html=True) # Handle Example Loading raw_example = "" if example_choice and example_choice != "— Custom Input —": try: raw_example = open(example_choice, 'r', encoding='utf-8').read() except Exception: raw_example = "" default_text = raw_example if raw_example else "SELECT * FROM uc_prod_apac_mdip_01.mydb.mytable" raw_text = st.text_area( "Paste your code here", value=default_text, height=400, label_visibility="collapsed" ) st.markdown("
", unsafe_allow_html=True) # compute parameterized output here so the Generate button (left) can persist it param_text = parameterize_script(raw_text, value_to_getter, as_fstring=as_fstring) header_tmp = "" if chosen_env: env_map_tmp = env_to_active.get(chosen_env, {}) header_tmp = format_env_prefix(chosen_env, env_map_tmp, key_to_getter) full_output_tmp = header_tmp + "\n\n" + param_text if header_tmp else param_text # Generate button moved to the left (near the input box) gcol1, gcol2 = st.columns([1, 2]) with gcol1: generate_clicked_left = st.button("Generate (Ctrl+Enter)", key="generate_btn_left", use_container_width=True) with gcol2: st.markdown("
Shortcut: Ctrl + Enter — or click Generate
", unsafe_allow_html=True) # If Generate clicked on the left, accept via keyboard trigger or click if generate_clicked_left: st.session_state['final_output'] = full_output_tmp st.success("Generated — final output saved") # show a brief on-screen hint when Ctrl+Enter is detected (visual feedback) if st.session_state.get('__ctrl_trigger') and st.session_state.get('__ctrl_trigger') != st.session_state.get('__last_hint_ts', ''): # display hint and set last_hint_ts so it doesn't re-fire repeatedly hint_html = """
Ctrl+Enter detected — press Generate now (or it will auto-click)
""" st.markdown(hint_html, unsafe_allow_html=True) st.session_state['__last_hint_ts'] = st.session_state.get('__ctrl_trigger') with col_out: st.markdown("
", unsafe_allow_html=True) st.markdown("**Parameterized Output**", unsafe_allow_html=True) # Only show preview and download after Generate has been clicked if st.session_state.get('final_output'): display_output = st.session_state.get('final_output') st.code(display_output, language="sql") # SQL highlighting works well for mixed content too # Copy/Download (shown only after Generate) c1, c2 = st.columns([1, 1]) with c1: st.download_button( "⬇️ Download Result", data=display_output, file_name="parameterized_script.txt", mime="text/plain", use_container_width=True ) else: st.info("👈 Click **Generate** to see the parameterized output here") st.markdown("
", unsafe_allow_html=True) # Client-side keyboard listener (Ctrl+Enter) — clicks the Generate button directly st.markdown( """ """, unsafe_allow_html=True, ) # End of UI (Step 3 removed as requested)