import streamlit as st
import pandas as pd
import io
import base64
import time
import tempfile
from datetime import datetime
from backend1_integration import chat_with_agents, build_index # (logic unchanged)
# ----------------------------------
# Page configuration
# ----------------------------------
st.set_page_config(
page_title="InsightPilot - AI PowerBI Report Assistant",
page_icon="🚀",
layout="wide",
initial_sidebar_state="collapsed"
)
# ----------------------------------
# CSS – compact, professional, boxed sections
# ----------------------------------
st.markdown("""
""", unsafe_allow_html=True)
# ----------------------------------
# Small helpers
# ----------------------------------
def create_download_link(file_path, file_name):
try:
with open(file_path, "rb") as f:
b64 = base64.b64encode(f.read()).decode()
return f'📥 Download Report PDF'
except FileNotFoundError:
return "❌ File not found. Please try generating the report again."
def extract_pdf_text(pdf_file):
try:
import fitz # PyMuPDF
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
tmp.write(pdf_file.read())
path = tmp.name
doc = fitz.open(path)
return "\n".join([p.get_text() for p in doc])
except Exception as e:
st.error(f"Error reading PDF: {str(e)}")
return None
# ----------------------------------
# App
# ----------------------------------
def main():
# ---- Header (now compact) ----
st.markdown("""
""", unsafe_allow_html=True)
with st.container():
st.markdown('', unsafe_allow_html=True)
# ---- Session state ----
for k, v in {
'analysis_complete': False,
'analysis_result': None,
'pdf_path': None,
'file_type': None,
'uploaded_file_name': None
}.items():
st.session_state.setdefault(k, v)
# ---- Select type ----
st.markdown('
📁 Select Analysis Type
', unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
csv_selected = st.button("📊 CSV Dataset Analysis", use_container_width=True)
with col2:
pdf_selected = st.button("📋 PDF Report Analysis", use_container_width=True)
if csv_selected:
st.session_state.file_type = "csv"
if pdf_selected:
st.session_state.file_type = "pdf"
# ---- Upload box (small) ----
if st.session_state.file_type:
st.markdown(f"""
Upload your {st.session_state.file_type.upper()} file
""", unsafe_allow_html=True)
if st.session_state.file_type == "csv":
uploaded_file = st.file_uploader(
"Choose a CSV file",
type=['csv'],
help="Upload your file for AI analysis.",
label_visibility="collapsed",
key="csv_uploader"
)
else:
uploaded_file = st.file_uploader(
"Choose a PDF file",
type=['pdf'],
help="Upload your file for AI analysis.",
label_visibility="collapsed",
key="pdf_uploader"
)
if uploaded_file is not None:
st.session_state.uploaded_file_name = uploaded_file.name
size_mb = len(uploaded_file.getvalue()) / 1024 / 1024
st.markdown(f"""
✅ File uploaded successfully!
📄 Name: {uploaded_file.name}
📏 Size: {size_mb:.2f} MB
🗂️ Type: {st.session_state.file_type.upper()} Analysis
""", unsafe_allow_html=True)
# ---- CSV preview - inside a card ----
if st.session_state.file_type == "csv":
try:
df = pd.read_csv(uploaded_file, encoding='latin-1')
st.markdown('
', unsafe_allow_html=True)
st.markdown("### 👀 Dataset Preview")
st.write(f"**Shape:** {df.shape[0]} rows × {df.shape[1]} columns")
st.dataframe(df.head(), use_container_width=True)
st.markdown('
', unsafe_allow_html=True)
except Exception as e:
st.error(f"Error reading CSV file: {str(e)}")
# ---- Start analysis button ----
if st.button("🔍 Start AI Analysis", use_container_width=True):
with st.spinner("🔧 Initializing AI systems and analyzing your data..."):
try:
query_engine = build_index()
if st.session_state.file_type == "csv":
file_content = io.BytesIO(uploaded_file.getvalue())
else:
pdf_text = extract_pdf_text(uploaded_file)
if pdf_text is None:
st.error("Failed to extract text from PDF. Please try again.")
st.stop()
file_content = pdf_text
result, pdf_path = chat_with_agents(
file_type=st.session_state.file_type,
file_content=file_content,
query_engine=query_engine
)
st.session_state.analysis_result = result
st.session_state.pdf_path = pdf_path
st.session_state.analysis_complete = True
st.success("✅ Analysis complete!")
except Exception as e:
st.markdown(f"""
❌ Analysis failed: {str(e)}
""", unsafe_allow_html=True)
# ---- Results (inside cards) ----
if st.session_state.analysis_complete and st.session_state.analysis_result:
st.markdown("---")
st.markdown('
', unsafe_allow_html=True)
st.markdown("## 📊 Analysis Results")
st.markdown("### 🎯 AI-Generated Insights")
st.markdown(st.session_state.analysis_result)
st.markdown('
', unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
st.markdown("### 📋 Generated Report Preview")
lines = str(st.session_state.analysis_result).split('\n')
preview_lines = [l for l in lines if l.strip() and not l.startswith(' ')][:5]
preview_text = '\n'.join(preview_lines)
st.markdown(f"""
**Report Summary:**
{preview_text}
**Generated:** {datetime.now().strftime('%B %d, %Y at %I:%M %p')}
**File Analyzed:** {st.session_state.uploaded_file_name}
**Analysis Type:** {st.session_state.file_type.upper()}
""")
st.markdown('
', unsafe_allow_html=True)
col1, col2, col3 = st.columns([1,2,1])
with col2:
if st.session_state.pdf_path:
with open(st.session_state.pdf_path, "rb") as pdf_file:
st.download_button(
label="📥 Download Full Report (PDF)",
data=pdf_file,
file_name=f"insightpilot_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf",
mime="application/pdf",
use_container_width=True
)
st.markdown("---")
col1, col2, col3 = st.columns([1,1,1])
with col2:
if st.button("🔄 Start New Analysis", use_container_width=True):
for key in [
'analysis_complete', 'analysis_result', 'pdf_path',
'file_type', 'uploaded_file_name'
]:
if key in st.session_state:
del st.session_state[key]
st.rerun()
# footer
st.markdown("""
""", unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True) # end container-narrow
if __name__ == "__main__":
main()