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('