Cliff / src /streamlit_app.py
shashankadari's picture
Update src/streamlit_app.py
3d1d971 verified
Raw History Blame Contribute Delete
24.9 kB
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(
"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
html, body, [class*="css"] {
font-family: 'Inter', sans-serif;
}
.stApp {
background-color: #f8fafc;
}
/* Card Styling */
.css-1r6slb0, .stMarkdown, .stBlock {
border-radius: 12px;
}
/* Expander panels (Reference Details) - give them a soft multi-color background */
div[data-testid="stExpander"] {
background: linear-gradient(180deg, rgba(124,58,237,0.03), rgba(6,182,212,0.02));
border-radius: 10px;
padding: 10px 12px;
box-shadow: 0 6px 18px rgba(15, 23, 42, 0.05);
border: 1px solid rgba(2, 6, 23, 0.06);
}
/* make the inner content look card-like and use accents */
div[data-testid="stExpander"] > div {
background: linear-gradient(180deg, rgba(255,255,255,0.92), rgba(250,250,255,0.95));
border-radius: 8px; padding: 8px; border: 1px solid rgba(2,6,23,0.02);
}
/* Expander headers (make header bar darker / high contrast) */
div[data-testid="stExpander"] > div[role="button"],
div[data-testid="stExpander"] > button,
div[data-testid="stExpander"] summary,
div[data-testid="stExpander"] .streamlit-expanderHeader {
background: linear-gradient(90deg, rgba(124,58,237,0.25), rgba(6,182,212,0.15));
color: #061425; font-weight:700; padding:8px 12px; border-radius:8px; margin-bottom:8px;
}
/* Tabs inside expanders (env tabs) - make text darker and active underline visible */
div[data-testid="stTabs"] button, div[data-testid="stExpander"] .stTabs button{
color: rgba(12, 18, 24, 0.85) !important; font-weight:600;
}
div[data-testid="stTabs"] button[aria-selected='true'], div[data-testid="stExpander"] .stTabs button[aria-selected='true']{
border-bottom: 3px solid rgba(239, 68, 68, 0.85) !important; color: rgba(239, 68, 68, 0.9) !important;
}
/* Headers */
h1, h2, h3 {
color: #1e293b;
font-weight: 700;
}
h1 {
font-size: 2.2rem;
/* multi-color header gradient */
background: -webkit-linear-gradient(90deg, #7c3aed 0%, #06b6d4 45%, #f59e0b 85%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
letter-spacing: 0.6px;
}
/* Custom Classes */
.metric-card {
/* soft pastel gradient for each card (subtle) */
background: linear-gradient(180deg, rgba(125,211,252,0.08), rgba(124,58,237,0.03));
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
text-align: center;
border: 1px solid rgba(2,6,23,0.06);
}
.metric-value {
font-size: 24px;
font-weight: bold;
color: #7c3aed;
}
.metric-label {
font-size: 14px;
color: #64748b;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.step-header {
font-size: 1.2rem;
font-weight: 600;
color: #334155;
margin-bottom: 1rem;
display: flex;
align-items: center;
gap: 8px;
}
.step-number {
background: linear-gradient(90deg, rgba(124,58,237,0.12), rgba(6,182,212,0.08));
color: #7c3aed;
width: 28px;
height: 28px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.9rem;
font-weight: bold;
}
/* Button Styling */
.stButton button {
background-color: #2563eb;
color: white;
border-radius: 8px;
padding: 0.5rem 1rem;
font-weight: 600;
border: none;
transition: all 0.2s;
}
.stButton button:hover {
background-color: #1d4ed8;
box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2);
}
/* Success Message */
.success-box {
padding: 1rem;
background-color: #f0fdf4;
border: 1px solid #bbf7d0;
border-radius: 8px;
color: #166534;
margin-bottom: 1rem;
}
/* Input / Output panels - soft colored cards */
.input-card { background: linear-gradient(180deg, rgba(7,89,133,0.03), rgba(124,58,237,0.02)); border-radius:10px; padding:12px; }
.output-card { background: linear-gradient(180deg, rgba(249,204,146,0.03), rgba(6,182,212,0.02)); border-radius:10px; padding:12px; }
/* Section 3: styled tables and DataFrame themes to match app palette */
/* Streamlit renders tables inside .stDataFrame and .stTable - target nested table elements */
.stDataFrame table, .stTable table, .stExpander table {
border-collapse: collapse; width: 100%; font-family: Inter, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue';
border-radius: 8px; overflow: hidden; box-shadow: 0 8px 16px rgba(15, 23, 42, 0.06);
}
.stDataFrame thead th, .stTable thead th, .stExpander thead th {
background: linear-gradient(90deg, rgba(124,58,237,0.13), rgba(6,182,212,0.09));
color: #052127; font-weight:700; padding: 10px 12px; text-align:left; border-bottom: 1px solid rgba(2,6,23,0.06);
}
.stDataFrame tbody td, .stTable tbody td, .stExpander tbody td {
padding: 10px 12px; color: #0f172a; border-bottom: 1px solid rgba(2,6,23,0.04);
}
/* Zebra rows */
.stDataFrame tbody tr:nth-child(odd), .stTable tbody tr:nth-child(odd), .stExpander tbody tr:nth-child(odd) {
background: linear-gradient(90deg, rgba(255,255,255,0.6), rgba(255,255,255,0.6));
}
.stDataFrame tbody tr:nth-child(even), .stTable tbody tr:nth-child(even), .stExpander tbody tr:nth-child(even) {
background: linear-gradient(90deg, rgba(250,250,255,0.85), rgba(248,255,250,0.85));
}
/* Small header pill accent on tables */
.stDataFrame thead th:first-child::before, .stTable thead th:first-child::before {
content: ""; display:inline-block; width:8px; height:8px; border-radius: 2px; margin-right:8px; background: linear-gradient(90deg,#7c3aed,#06b6d4); vertical-align:middle;
}
/* JSON/st.json / pre blocks - make them friendly too */
.stJson, pre, code { background:#fbfbfd; color:#052127; border-radius:8px; padding:8px; border:1px solid rgba(2,6,23,0.04); }
</style>
""",
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(
"""
<style>
.stApp { background: linear-gradient(180deg,#071025 0%, #051426 100%); color: #e6eef6; }
.metric-card { background: linear-gradient(180deg, rgba(124,58,237,0.06), rgba(6,182,212,0.02)); border: 1px solid rgba(255,255,255,0.03); }
h1, h2, .stSubheader { color: #ffd7a6; }
.step-number { color: #ffd7a6; }
div[data-testid="stExpander"] { background: linear-gradient(180deg, rgba(7,10,20,0.25), rgba(6,14,28,0.18)); }
.input-card, .output-card { background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01)); }
.stDataFrame thead th, .stTable thead th, .stExpander thead th { color: #e6eef6; }
.stDataFrame tbody td, .stTable tbody td, .stExpander tbody td { color: #cfeafc; }
</style>
""",
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("<br>", unsafe_allow_html=True)
# Step 1: Upload
st.markdown('<div class="step-header"><div class="step-number">1</div>Upload Configuration</div>', 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"""
<div class="metric-card">
<div class="metric-value">{len(value_to_getter)}</div>
<div class="metric-label">Mappings Found</div>
</div>
""",
unsafe_allow_html=True
)
with cols[1]:
st.markdown(
f"""
<div class="metric-card">
<div class="metric-value">{len(env_to_active)}</div>
<div class="metric-label">Environments</div>
</div>
""",
unsafe_allow_html=True
)
with cols[2]:
st.markdown(
f"""
<div class="metric-card">
<div class="metric-value">{len(key_to_getter)}</div>
<div class="metric-label">Active Keys</div>
</div>
""",
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("<br>", unsafe_allow_html=True)
# Step 2: Workspace
st.markdown('<div class="step-header"><div class="step-number">2</div>Parameterize Code</div>', 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("<div class='input-card card'>", 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("</div>", 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("<div style='margin-top:8px;color:#475569;font-weight:600;'>Shortcut: <kbd style='background:#111827;color:#fff;border-radius:4px;padding:2px 6px;'>Ctrl</kbd> + <kbd style='background:#111827;color:#fff;border-radius:4px;padding:2px 6px;'>Enter</kbd> β€” or click Generate</div>", 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 = """
<div id='ctrl-hint' style='padding:8px 12px;border-radius:8px;background:linear-gradient(90deg,#7c3aed,#06b6d4);color:white;display:inline-block;box-shadow:0 4px 12px rgba(0,0,0,0.08);font-weight:700;'>
Ctrl+Enter detected β€” press Generate now (or it will auto-click)
</div>
<script>
// fade-out after 1400ms
setTimeout(()=>{ const el=document.getElementById('ctrl-hint'); if(el){ el.style.transition='opacity 0.6s'; el.style.opacity='0'; } }, 1400);
</script>
"""
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("<div class='output-card card'>", 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("</div>", unsafe_allow_html=True)
# Client-side keyboard listener (Ctrl+Enter) β€” clicks the Generate button directly
st.markdown(
"""
<script>
document.addEventListener('keydown', function(e){
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter'){
// click the Generate button directly
const buttons = Array.from(document.querySelectorAll('button'));
const genBtn = buttons.find(b => b.innerText && b.innerText.trim().startsWith('Generate'));
if (genBtn){ genBtn.click(); }
}
});
</script>
""",
unsafe_allow_html=True,
)
# End of UI (Step 3 removed as requested)