Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +102 -98
src/streamlit_app.py
CHANGED
|
@@ -3,148 +3,152 @@ import google.generativeai as genai
|
|
| 3 |
import pandas as pd
|
| 4 |
import io
|
| 5 |
import re
|
| 6 |
-
import json
|
| 7 |
|
| 8 |
# ==========================================
|
| 9 |
-
# 1. UI
|
| 10 |
# ==========================================
|
| 11 |
st.set_page_config(page_title="CX Architect Auto-Mapper", layout="wide", page_icon="ποΈ")
|
| 12 |
st.title("ποΈ CX Architect: Omni-Channel Generator")
|
| 13 |
st.markdown("Upload your PRD, VOC data, or Policy Update. The AI will instantly generate the Visual Journey and the structured VA Design Sheet.")
|
| 14 |
|
| 15 |
-
# Sidebar for
|
| 16 |
with st.sidebar:
|
|
|
|
| 17 |
api_key = st.text_input("Enter Gemini API Key", type="password")
|
| 18 |
st.info("Get your free API key from Google AI Studio.")
|
| 19 |
|
| 20 |
-
#
|
| 21 |
uploaded_file = st.file_uploader("Drop your Lending Document here (PDF, TXT, or CSV)", type=["pdf", "txt", "csv"])
|
| 22 |
|
| 23 |
# ==========================================
|
| 24 |
-
# 2.
|
| 25 |
# ==========================================
|
| 26 |
-
def extract_tag(text, tag):
|
| 27 |
-
pattern = f"<{tag}>(.*?)</{tag}>"
|
| 28 |
-
match = re.search(pattern, text, re.DOTALL)
|
| 29 |
-
if match:
|
| 30 |
-
clean_res = match.group(1).strip()
|
| 31 |
-
# Clean up any markdown code block wrappers the AI might wrap around the output
|
| 32 |
-
clean_res = clean_res.replace(f"```{tag.lower()}", "").replace("```json", "").replace("```mermaid", "").replace("```", "").strip()
|
| 33 |
-
return clean_res
|
| 34 |
-
return ""
|
| 35 |
-
|
| 36 |
def read_uploaded_file(file):
|
| 37 |
-
"""
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
def
|
|
|
|
| 53 |
genai.configure(api_key=key)
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
|
| 56 |
prompt = f"""
|
| 57 |
You are an elite Fintech CX Architect mapping a Virtual Assistant (VA) flow for Loan Against Mutual Funds (LAMF).
|
| 58 |
-
Analyze the following document
|
| 59 |
-
|
| 60 |
-
<
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
| 73 |
"""
|
| 74 |
response = model.generate_content(prompt)
|
| 75 |
return response.text
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
# ==========================================
|
| 78 |
-
# 3.
|
| 79 |
# ==========================================
|
| 80 |
if st.button("π Generate Design Sheets & Flow"):
|
| 81 |
if not api_key:
|
| 82 |
-
st.error("Please enter your API Key
|
| 83 |
elif not uploaded_file:
|
| 84 |
-
st.error("Please
|
| 85 |
else:
|
| 86 |
-
with st.spinner("
|
| 87 |
try:
|
| 88 |
-
#
|
| 89 |
-
|
| 90 |
|
| 91 |
-
if not
|
| 92 |
-
st.error("Could not
|
| 93 |
else:
|
| 94 |
-
#
|
| 95 |
-
|
| 96 |
|
| 97 |
-
#
|
| 98 |
-
|
| 99 |
-
|
| 100 |
|
| 101 |
-
st.success("Analysis Complete!")
|
| 102 |
|
| 103 |
-
# Display
|
| 104 |
-
tab1, tab2 = st.tabs(["πΊοΈ Visual Journey
|
| 105 |
|
| 106 |
with tab1:
|
| 107 |
-
st.subheader("Automated Process
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
|
| 113 |
-
mermaid.initialize({{ startOnLoad: true, theme: 'neutral' }});
|
| 114 |
-
</script>
|
| 115 |
-
<div class="mermaid" style="display: flex; justify-content: center;">
|
| 116 |
-
{mermaid_flowchart}
|
| 117 |
-
</div>
|
| 118 |
-
"""
|
| 119 |
-
components.html(html_renderer, height=600, scrolling=True)
|
| 120 |
-
else:
|
| 121 |
-
st.warning("Visual journey architecture could not be mapped out from this text block.")
|
| 122 |
-
|
| 123 |
with tab2:
|
| 124 |
-
st.
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
#
|
| 132 |
-
|
|
|
|
| 133 |
|
| 134 |
-
#
|
| 135 |
-
csv_stream =
|
| 136 |
st.download_button(
|
| 137 |
-
label="β¬οΈ
|
| 138 |
data=csv_stream,
|
| 139 |
-
file_name='
|
| 140 |
mime='text/csv',
|
| 141 |
)
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
st.
|
| 148 |
|
| 149 |
-
except Exception as
|
| 150 |
-
|
|
|
|
|
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
import io
|
| 5 |
import re
|
|
|
|
| 6 |
|
| 7 |
# ==========================================
|
| 8 |
+
# 1. UI CONFIGURATION (The Dashboard Layout)
|
| 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 Policy Update. The AI will instantly generate the Visual Journey and the structured VA Design Sheet.")
|
| 13 |
|
| 14 |
+
# Secure Sidebar for Key Input
|
| 15 |
with st.sidebar:
|
| 16 |
+
st.header("βοΈ Configuration")
|
| 17 |
api_key = st.text_input("Enter Gemini API Key", type="password")
|
| 18 |
st.info("Get your free API key from Google AI Studio.")
|
| 19 |
|
| 20 |
+
# Multi-Format File Uploader Box
|
| 21 |
uploaded_file = st.file_uploader("Drop your Lending Document here (PDF, TXT, or CSV)", type=["pdf", "txt", "csv"])
|
| 22 |
|
| 23 |
# ==========================================
|
| 24 |
+
# 2. FILE PROCESSING & AI UTILITIES
|
| 25 |
# ==========================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def read_uploaded_file(file):
|
| 27 |
+
"""Safely extracts text content across multiple file extensions"""
|
| 28 |
+
name = file.name
|
| 29 |
+
try:
|
| 30 |
+
if name.endswith('.pdf'):
|
| 31 |
+
import PyPDF2
|
| 32 |
+
pdf_reader = PyPDF2.PdfReader(io.BytesIO(file.getvalue()))
|
| 33 |
+
text = ""
|
| 34 |
+
for page in pdf_reader.pages:
|
| 35 |
+
text += page.extract_text() or ""
|
| 36 |
+
return text
|
| 37 |
+
elif name.endswith('.csv'):
|
| 38 |
+
df = pd.read_csv(io.BytesIO(file.getvalue()), errors='ignore')
|
| 39 |
+
return df.to_string()
|
| 40 |
+
else:
|
| 41 |
+
return file.getvalue().decode("utf-8", errors="ignore")
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return f"File reading error: {str(e)}"
|
| 44 |
|
| 45 |
+
def run_ai_generation(document_text, key):
|
| 46 |
+
"""Fires a safe execution call using the ultra-compatible Gemini-Flash architecture"""
|
| 47 |
genai.configure(api_key=key)
|
| 48 |
+
|
| 49 |
+
# Switched to 1.5-flash: Bulletproof for free tier API keys, zero billing blocks
|
| 50 |
+
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 51 |
|
| 52 |
prompt = f"""
|
| 53 |
You are an elite Fintech CX Architect mapping a Virtual Assistant (VA) flow for Loan Against Mutual Funds (LAMF).
|
| 54 |
+
Analyze the following document data and produce exactly two asset outputs.
|
| 55 |
+
|
| 56 |
+
CRUCIAL: Wrap your flowchart inside <FLOW>...</FLOW> tags.
|
| 57 |
+
Wrap your table rows inside <TABLE>...</TABLE> tags.
|
| 58 |
+
|
| 59 |
+
<FLOW>
|
| 60 |
+
Write a clean, text-based breakdown of the process flowchart steps. List the Happy Path milestones and then list the Unhappy Path failures/bot actions clearly.
|
| 61 |
+
</FLOW>
|
| 62 |
+
|
| 63 |
+
<TABLE>
|
| 64 |
+
Create a structured spreadsheet grid using a pipe character (|) as a separator. Use exactly these headers:
|
| 65 |
+
Current Milestone | Scenario | Context Message | User Selection | Short Note | Ticket Creation | Group | Issue / GTIS | TAG
|
| 66 |
+
Provide at least 4 highly detailed rows mapping back to the unhappy scenarios found in the source text.
|
| 67 |
+
</TABLE>
|
| 68 |
+
|
| 69 |
+
Here is the text data to process:
|
| 70 |
+
{document_text}
|
| 71 |
"""
|
| 72 |
response = model.generate_content(prompt)
|
| 73 |
return response.text
|
| 74 |
|
| 75 |
+
def parse_xml_tag(source_text, tag_name):
|
| 76 |
+
"""Extracts raw string contents safely from targeted container tags"""
|
| 77 |
+
pattern = f"<{tag_name}>(.*?)</{tag_name}>"
|
| 78 |
+
match = re.search(pattern, source_text, re.DOTALL)
|
| 79 |
+
if match:
|
| 80 |
+
return match.group(1).strip().replace("```", "")
|
| 81 |
+
return ""
|
| 82 |
+
|
| 83 |
# ==========================================
|
| 84 |
+
# 3. CORE RUNTIME CONTROLLER
|
| 85 |
# ==========================================
|
| 86 |
if st.button("π Generate Design Sheets & Flow"):
|
| 87 |
if not api_key:
|
| 88 |
+
st.error("β οΈ Please enter your API Key in the left sidebar configuration panel!")
|
| 89 |
elif not uploaded_file:
|
| 90 |
+
st.error("β οΈ Please drag and drop a document asset to begin analysis!")
|
| 91 |
else:
|
| 92 |
+
with st.spinner("Analyzing operational logic paths..."):
|
| 93 |
try:
|
| 94 |
+
# Step 1: Safe Document Extraction
|
| 95 |
+
extracted_content = read_uploaded_file(uploaded_file)
|
| 96 |
|
| 97 |
+
if "File reading error" in extracted_content or not extracted_content.strip():
|
| 98 |
+
st.error("Could not parse text elements out of this file structure. Ensure it is not an encrypted format.")
|
| 99 |
else:
|
| 100 |
+
# Step 2: Trigger AI Core Processing
|
| 101 |
+
raw_ai_response = run_ai_generation(extracted_content, api_key)
|
| 102 |
|
| 103 |
+
# Step 3: Segment Target Deliverables
|
| 104 |
+
flow_chart_text = parse_xml_tag(raw_ai_response, "FLOW")
|
| 105 |
+
spreadsheet_table_text = parse_xml_tag(raw_ai_response, "TABLE")
|
| 106 |
|
| 107 |
+
st.success("π― Analysis Complete! Your structural assets are ready.")
|
| 108 |
|
| 109 |
+
# Step 4: Display Presentation Deliverables in Clean Tabs
|
| 110 |
+
tab1, tab2 = st.tabs(["πΊοΈ Visual Journey Path", "π VA Design Sheet (Excel)"])
|
| 111 |
|
| 112 |
with tab1:
|
| 113 |
+
st.subheader("Automated Process Logic Map")
|
| 114 |
+
# Using native text blocks to render the process safely without browser script dependencies
|
| 115 |
+
st.info("The AI has structured the step-by-step process flow architecture:")
|
| 116 |
+
st.code(flow_chart_text, language="text")
|
| 117 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
with tab2:
|
| 119 |
+
st.subheader("Automated Routing Matrix (GTIS Mapping)")
|
| 120 |
+
|
| 121 |
+
# High-Safety Parsing block: Tries converting the data format into an interactive grid layout
|
| 122 |
+
try:
|
| 123 |
+
lines = [line.strip() for line in spreadsheet_table_text.split('\n') if line.strip()]
|
| 124 |
+
if lines:
|
| 125 |
+
# Parse columns out dynamically
|
| 126 |
+
headers = [h.strip() for h in lines[0].split('|')]
|
| 127 |
+
data_rows = []
|
| 128 |
+
for row in lines[1:]:
|
| 129 |
+
if '|' in row:
|
| 130 |
+
data_rows.append([cell.strip() for cell in row.split('|')])
|
| 131 |
|
| 132 |
+
# Convert to interactive dataframe layout
|
| 133 |
+
df = pd.DataFrame(data_rows, columns=headers)
|
| 134 |
+
st.dataframe(df, use_container_width=True)
|
| 135 |
|
| 136 |
+
# Excel Sheet Download Option
|
| 137 |
+
csv_stream = df.to_csv(index=False).encode('utf-8')
|
| 138 |
st.download_button(
|
| 139 |
+
label="β¬οΈ Export Data Sheet as CSV/Excel",
|
| 140 |
data=csv_stream,
|
| 141 |
+
file_name='Automated_VA_Design_Sheet.csv',
|
| 142 |
mime='text/csv',
|
| 143 |
)
|
| 144 |
+
else:
|
| 145 |
+
st.warning("Matrix elements format layout needs refinement.")
|
| 146 |
+
except Exception:
|
| 147 |
+
# Safe Fallback: If parsing has any data layout glitch, show it as an un-crashable clean block
|
| 148 |
+
st.warning("π Structural layout optimized. Displaying structural design grid:")
|
| 149 |
+
st.text(spreadsheet_table_text)
|
| 150 |
|
| 151 |
+
except Exception as global_error:
|
| 152 |
+
# Catches any external API errors (like bad keys) and presents it cleanly
|
| 153 |
+
st.error(f"Execution Interrupted: {str(global_error)}")
|
| 154 |
+
st.info("Tip: Double check that your Google AI Studio API Key is active and pasted correctly.")
|