atulsharma42 commited on
Commit
f2f12c3
Β·
verified Β·
1 Parent(s): fdef812

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +41 -41
src/streamlit_app.py CHANGED
@@ -5,38 +5,40 @@ import io
5
  import re
6
 
7
  # ==========================================
8
- # 1. GLOBAL INITIALIZATION & UI SETUP
9
  # ==========================================
10
  st.set_page_config(page_title="CX Architect Auto-Mapper", layout="wide", page_icon="πŸ—οΈ")
11
  st.title("πŸ—οΈ CX Architect: Omni-Channel Generator")
12
  st.markdown("Upload your PRD, VOC data, or an existing spreadsheet. The AI engine will instantly map the customer journey and generate a structured VA Design Sheet.")
13
 
14
- # Initialize variables at the very top to prevent any scope or NameError crashes
15
- api_key = ""
16
- demo_mode = False
17
-
18
- # Configuration Sidebar Panel
19
  with st.sidebar:
20
  st.header("βš™οΈ Configuration")
21
 
22
- # Fail-safe Toggle for Presentation Stability
23
  demo_mode = st.toggle("πŸš€ Activate Demo Simulation Mode", value=False, help="Turn this ON if your Google API Key is unavailable or restricted.")
24
 
25
- if not demo_mode:
26
- api_key = st.text_input("Enter Gemini API Key", type="password")
27
- if api_key.startswith("AQ."):
28
- st.warning("⚠️ Restricted 'AQ.' token detected. If it fails, switch to Demo Simulation Mode.")
29
- else:
 
 
 
 
30
  st.success("🟒 Simulation Mode Active (No Key Required)")
 
 
31
 
32
  st.markdown("---")
33
  st.markdown("**Framework: LAMF Process Automation Engine**")
34
 
35
- # File Selection Support Box
36
  uploaded_file = st.file_uploader("Drop your Lending Document here (PDF, TXT, or CSV)", type=["pdf", "txt", "csv"])
37
 
38
  # ==========================================
39
- # 2. CORE STORAGE FOR SIMULATED RUNS
40
  # ==========================================
41
  def get_simulation_assets():
42
  """Returns high-fidelity layout data modeled directly from real lending datasets"""
@@ -68,8 +70,23 @@ def get_simulation_assets():
68
  ]
69
  return flow_text, pd.DataFrame(rows, columns=headers)
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  # ==========================================
72
- # 3. INTERFACE EXECUTION RUNTIME
73
  # ==========================================
74
  if st.button("πŸš€ Generate Design Sheets & Flow"):
75
  if not demo_mode and not api_key:
@@ -78,12 +95,10 @@ if st.button("πŸš€ Generate Design Sheets & Flow"):
78
  st.error("⚠️ Data Source Missing! Please upload a PDF, TXT, or CSV file to analyze.")
79
  else:
80
  with st.spinner("Processing document datasets and structural journey parameters..."):
81
-
82
- # Setup container objects to capture outputs securely
83
- flow_output = ""
84
- dataframe_output = None
85
-
86
  try:
 
 
 
87
  # SCENARIO A: Direct Presentation Simulation Mode
88
  if demo_mode:
89
  flow_output, dataframe_output = get_simulation_assets()
@@ -92,20 +107,11 @@ if st.button("πŸš€ Generate Design Sheets & Flow"):
92
  elif uploaded_file.name.endswith('.csv'):
93
  raw_df = pd.read_csv(io.BytesIO(uploaded_file.getvalue()), errors='ignore')
94
  dataframe_output = raw_df
95
- flow_output = f"πŸ“‹ Native Document File Detected: '{uploaded_file.name}'\nSuccessfully loaded {len(raw_df)} workflow configuration rows directly into the dashboard matrix view."
96
 
97
  # SCENARIO C: Live AI Extraction Mode
98
  else:
99
- # Read the file bytes safely
100
- file_name = uploaded_file.name
101
- if file_name.endswith('.pdf'):
102
- import PyPDF2
103
- pdf_reader = PyPDF2.PdfReader(io.BytesIO(uploaded_file.getvalue()))
104
- doc_text = "".join([page.extract_text() or "" for page in pdf_reader.pages])
105
- else:
106
- doc_text = uploaded_file.getvalue().decode("utf-8", errors="ignore")
107
-
108
- # Fire API Engine
109
  genai.configure(api_key=api_key)
110
  model = genai.GenerativeModel('gemini-1.5-flash')
111
 
@@ -127,20 +133,17 @@ if st.button("πŸš€ Generate Design Sheets & Flow"):
127
  """
128
  ai_response = model.generate_content(prompt).text
129
 
130
- # Parse out string chunks safely
131
  flow_match = re.search(r"<FLOW>(.*?)</FLOW>", ai_response, re.DOTALL)
132
  table_match = re.search(r"<TABLE>(.*?)</TABLE>", ai_response, re.DOTALL)
133
 
134
- flow_output = flow_match.group(1).strip().replace("```", "") if flow_match else "Journey breakdown completed."
135
- raw_table_str = table_match.group(1).strip().replace("```", "") if table_match else ""
136
 
137
- # Construct dataframe cleanly
138
  table_lines = [l.strip() for l in raw_table_str.split('\n') if l.strip() and '---' not in l]
139
  if table_lines:
140
  headers = [h.strip() for h in table_lines[0].split('|')]
141
  data_rows = [[cell.strip() for cell in r.split('|')] for r in table_lines[1:] if '|' in r]
142
 
143
- # Adjust widths to keep columns uniform
144
  clean_rows = []
145
  for row in data_rows:
146
  if len(row) < len(headers): row += ["NA"] * (len(headers) - len(row))
@@ -149,7 +152,7 @@ if st.button("πŸš€ Generate Design Sheets & Flow"):
149
  dataframe_output = pd.DataFrame(clean_rows, columns=headers)
150
 
151
  # ==========================================
152
- # 4. RENDER PRESENTATION DELIVERABLES
153
  # ==========================================
154
  st.success("🎯 Assets Computed Successfully!")
155
  tab1, tab2 = st.tabs(["πŸ—ΊοΈ Visual Journey Path", "πŸ“Š VA Design Sheet (Excel)"])
@@ -162,10 +165,8 @@ if st.button("πŸš€ Generate Design Sheets & Flow"):
162
  with tab2:
163
  st.subheader("Automated Routing Matrix (GTIS Mapping)")
164
  if dataframe_output is not None:
165
- # Render interactive grid layout
166
  st.dataframe(dataframe_output, use_container_width=True)
167
 
168
- # Direct file download stream
169
  csv_stream = dataframe_output.to_csv(index=False).encode('utf-8')
170
  st.download_button(
171
  label="⬇️ Download Sheet as CSV/Excel",
@@ -177,5 +178,4 @@ if st.button("πŸš€ Generate Design Sheets & Flow"):
177
  st.warning("Data rows could not be arranged into a standard matrix framework layout.")
178
 
179
  except Exception as runtime_err:
180
- st.error(f"Execution Interrupted: {str(runtime_err)}")
181
- st.info("πŸ’‘ Presentation Hack: Simply toggle 'Activate Demo Simulation Mode' in the sidebar to bypass any technical blocks instantly.")
 
5
  import re
6
 
7
  # ==========================================
8
+ # 1. UI CONFIGURATION & SECURE SETUP
9
  # ==========================================
10
  st.set_page_config(page_title="CX Architect Auto-Mapper", layout="wide", page_icon="πŸ—οΈ")
11
  st.title("πŸ—οΈ CX Architect: Omni-Channel Generator")
12
  st.markdown("Upload your PRD, VOC data, or an existing spreadsheet. The AI engine will instantly map the customer journey and generate a structured VA Design Sheet.")
13
 
14
+ # Sidebar Configuration Panel
 
 
 
 
15
  with st.sidebar:
16
  st.header("βš™οΈ Configuration")
17
 
18
+ # 1. Toggle for Demo Simulation Mode
19
  demo_mode = st.toggle("πŸš€ Activate Demo Simulation Mode", value=False, help="Turn this ON if your Google API Key is unavailable or restricted.")
20
 
21
+ # 2. Key Input - ALWAYS evaluated so it NEVER throws a NameError, but disabled if Demo Mode is active
22
+ api_key = st.text_input(
23
+ "Enter Gemini API Key",
24
+ type="password",
25
+ disabled=demo_mode,
26
+ placeholder="Paste your AIza... key here"
27
+ )
28
+
29
+ if demo_mode:
30
  st.success("🟒 Simulation Mode Active (No Key Required)")
31
+ elif api_key.startswith("AQ."):
32
+ st.warning("⚠️ Restricted 'AQ.' token detected. If it fails, switch to Demo Simulation Mode.")
33
 
34
  st.markdown("---")
35
  st.markdown("**Framework: LAMF Process Automation Engine**")
36
 
37
+ # Multi-Format File Selection Box
38
  uploaded_file = st.file_uploader("Drop your Lending Document here (PDF, TXT, or CSV)", type=["pdf", "txt", "csv"])
39
 
40
  # ==========================================
41
+ # 2. DATA PROCESSING & SIMULATION LAYOUTS
42
  # ==========================================
43
  def get_simulation_assets():
44
  """Returns high-fidelity layout data modeled directly from real lending datasets"""
 
70
  ]
71
  return flow_text, pd.DataFrame(rows, columns=headers)
72
 
73
+ def safe_read_file(file):
74
+ name = file.name
75
+ try:
76
+ if name.endswith('.pdf'):
77
+ import PyPDF2
78
+ pdf_reader = PyPDF2.PdfReader(io.BytesIO(file.getvalue()))
79
+ return "".join([page.extract_text() or "" for page in pdf_reader.pages])
80
+ elif name.endswith('.csv'):
81
+ df = pd.read_csv(io.BytesIO(file.getvalue()), errors='ignore')
82
+ return df.to_string()
83
+ else:
84
+ return file.getvalue().decode("utf-8", errors="ignore")
85
+ except Exception as e:
86
+ return f"Error: {str(e)}"
87
+
88
  # ==========================================
89
+ # 3. RUNTIME CONTROLLER
90
  # ==========================================
91
  if st.button("πŸš€ Generate Design Sheets & Flow"):
92
  if not demo_mode and not api_key:
 
95
  st.error("⚠️ Data Source Missing! Please upload a PDF, TXT, or CSV file to analyze.")
96
  else:
97
  with st.spinner("Processing document datasets and structural journey parameters..."):
 
 
 
 
 
98
  try:
99
+ flow_output = ""
100
+ dataframe_output = None
101
+
102
  # SCENARIO A: Direct Presentation Simulation Mode
103
  if demo_mode:
104
  flow_output, dataframe_output = get_simulation_assets()
 
107
  elif uploaded_file.name.endswith('.csv'):
108
  raw_df = pd.read_csv(io.BytesIO(uploaded_file.getvalue()), errors='ignore')
109
  dataframe_output = raw_df
110
+ flow_output = f"πŸ“‹ Native Document File Detected: '{uploaded_file.name}'\nSuccessfully loaded {len(raw_df)} rows directly into the matrix view."
111
 
112
  # SCENARIO C: Live AI Extraction Mode
113
  else:
114
+ doc_text = safe_read_file(uploaded_file)
 
 
 
 
 
 
 
 
 
115
  genai.configure(api_key=api_key)
116
  model = genai.GenerativeModel('gemini-1.5-flash')
117
 
 
133
  """
134
  ai_response = model.generate_content(prompt).text
135
 
 
136
  flow_match = re.search(r"<FLOW>(.*?)</FLOW>", ai_response, re.DOTALL)
137
  table_match = re.search(r"<TABLE>(.*?)</TABLE>", ai_response, re.DOTALL)
138
 
139
+ flow_output = flow_match.group(1).strip() if flow_match else "Journey breakdown completed."
140
+ raw_table_str = table_match.group(1).strip() if table_match else ""
141
 
 
142
  table_lines = [l.strip() for l in raw_table_str.split('\n') if l.strip() and '---' not in l]
143
  if table_lines:
144
  headers = [h.strip() for h in table_lines[0].split('|')]
145
  data_rows = [[cell.strip() for cell in r.split('|')] for r in table_lines[1:] if '|' in r]
146
 
 
147
  clean_rows = []
148
  for row in data_rows:
149
  if len(row) < len(headers): row += ["NA"] * (len(headers) - len(row))
 
152
  dataframe_output = pd.DataFrame(clean_rows, columns=headers)
153
 
154
  # ==========================================
155
+ # 4. RENDER OUTPUT INTERFACE
156
  # ==========================================
157
  st.success("🎯 Assets Computed Successfully!")
158
  tab1, tab2 = st.tabs(["πŸ—ΊοΈ Visual Journey Path", "πŸ“Š VA Design Sheet (Excel)"])
 
165
  with tab2:
166
  st.subheader("Automated Routing Matrix (GTIS Mapping)")
167
  if dataframe_output is not None:
 
168
  st.dataframe(dataframe_output, use_container_width=True)
169
 
 
170
  csv_stream = dataframe_output.to_csv(index=False).encode('utf-8')
171
  st.download_button(
172
  label="⬇️ Download Sheet as CSV/Excel",
 
178
  st.warning("Data rows could not be arranged into a standard matrix framework layout.")
179
 
180
  except Exception as runtime_err:
181
+ st.error(f"Execution Interrupted: {str(runtime_err)}")