Shubham170793 commited on
Commit
190f0f1
Β·
verified Β·
1 Parent(s): 4ec6a61

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +120 -92
src/streamlit_app.py CHANGED
@@ -1,5 +1,5 @@
1
  # ==========================================================
2
- # streamlit_app.py β€” Restored Stable UI (Pre-rerun Fix)
3
  # ==========================================================
4
  import os
5
  import re
@@ -8,10 +8,11 @@ from ingestion import extract_text_from_pdf, chunk_text
8
  from vectorstore import build_faiss_index
9
  from qa import retrieve_chunks, generate_answer, cache_embeddings, embed_chunks, genai_generate
10
 
11
- st.set_page_config(page_title="Enterprise Knowledge Assistant", layout="wide")
 
12
 
13
  # ==========================================================
14
- # 🧭 SIDEBAR β€” Original Clean Version
15
  # ==========================================================
16
  with st.sidebar:
17
  st.markdown("### 🧭 Response Mode")
@@ -36,7 +37,7 @@ with st.sidebar:
36
  st.caption("✨ Built by Shubham Sharma")
37
 
38
  # ==========================================================
39
- # 🧠 SESSION STATE β€” Clean and Minimal
40
  # ==========================================================
41
  for key, val in {
42
  "user_query_input": "",
@@ -54,100 +55,127 @@ def set_user_query(q, idx):
54
  st.experimental_rerun()
55
 
56
  # ==========================================================
57
- # πŸ“˜ APP HEADER
58
  # ==========================================================
59
  st.markdown(
60
  """
61
- <h1 style="text-align:center;">πŸ“„ Enterprise Knowledge Assistant</h1>
62
- <p style="text-align:center;color:gray;">
63
- Query SAP documentation and enterprise PDFs β€” powered by reasoning and retrieval.
64
- </p>
 
 
65
  """,
66
  unsafe_allow_html=True,
67
  )
68
 
69
  # ==========================================================
70
- # πŸ“‚ DOCUMENT UPLOAD / SELECTION
71
  # ==========================================================
72
- st.markdown("### Select a document:")
73
- doc_choice = st.radio("", ("-- Select --", "Sample PDF", "Upload Custom PDF"))
74
-
75
- temp_path = None
76
- if doc_choice == "Sample PDF":
77
- temp_path = os.path.join(os.path.dirname(__file__), "sample.pdf")
78
- st.success("πŸ“˜ Sample PDF loaded successfully. Ask questions below.")
79
- elif doc_choice == "Upload Custom PDF":
80
- uploaded_file = st.file_uploader("Upload your PDF", type="pdf")
81
- if uploaded_file:
82
- temp_path = os.path.join("/tmp", uploaded_file.name)
83
- with open(temp_path, "wb") as f:
84
- f.write(uploaded_file.getbuffer())
85
- st.success(f"βœ… '{uploaded_file.name}' uploaded successfully β€” ready to query below.")
86
- else:
87
- st.info("⬅️ Please select or upload a document to begin.")
88
-
89
- # ==========================================================
90
- # 🧠 PROCESS DOCUMENT (only when selected)
91
- # ==========================================================
92
- if temp_path:
93
- text, toc = extract_text_from_pdf(temp_path)
94
- chunks = chunk_text(text, chunk_size=chunk_size, overlap=overlap)
95
- st.success("βœ… Document ready β€” you can now ask questions below.")
96
-
97
- embeddings = cache_embeddings(os.path.basename(temp_path), chunks, embed_chunks)
98
- index = build_faiss_index(embeddings)
99
-
100
- # ==========================================================
101
- # πŸ’¬ SUGGESTED QUESTIONS (Smart Defaults)
102
- # ==========================================================
103
- if not st.session_state["query_suggestions_fixed"]:
104
- st.session_state["query_suggestions_fixed"] = [
105
- "What is the purpose of this document?",
106
- "How can integration be set up in SAP Cloud?",
107
- "What are the prerequisites mentioned?",
108
- "What steps are involved in configuration?",
109
- "How to troubleshoot integration issues?",
110
- "What is the key functionality covered?"
111
- ]
112
-
113
- st.markdown("### Ask the Assistant")
114
-
115
- visible_qs = st.session_state["query_suggestions_fixed"][:3] if not st.session_state["show_more"] else st.session_state["query_suggestions_fixed"]
116
- cols = st.columns(3)
117
- for i, q in enumerate(visible_qs):
118
- if cols[i % 3].button(f"πŸ”Ή {q}", key=f"suggest_{i}"):
119
- set_user_query(q, i)
120
-
121
- if st.button("Show more β–Ό" if not st.session_state["show_more"] else "Show less β–²"):
122
- st.session_state["show_more"] = not st.session_state["show_more"]
123
-
124
- # ==========================================================
125
- # 🧩 QUERY INPUT
126
- # ==========================================================
127
- user_query = st.text_input("Type your question or click one above:", value=st.session_state["user_query_input"], key="user_query_input")
128
-
129
- # ==========================================================
130
- # πŸ€– GENERATE ANSWER
131
- # ==========================================================
132
- if user_query:
133
- reasoning_mode = mode == "Extended (Document + general)"
134
- st.markdown(f"**Mode:** {'🧠 Extended' if reasoning_mode else 'πŸ“„ Strict Document'}")
135
- with st.spinner("Thinking..."):
136
- retrieved = retrieve_chunks(user_query, index, chunks, top_k=top_k, embeddings=embeddings)
137
- answer = generate_answer(user_query, retrieved, reasoning_mode=reasoning_mode)
138
-
139
- st.markdown("### Assistant’s Answer")
140
- st.markdown(f"<div style='background:#0f172a;border-left:4px solid #3b82f6;padding:12px;border-radius:8px;color:#f1f5f9'>{answer}</div>", unsafe_allow_html=True)
141
-
142
- with st.expander("πŸ“˜ Supporting Context", expanded=False):
143
- for i, chunk in enumerate(retrieved, 1):
144
- st.markdown(f"**Chunk {i}:** {chunk.strip()}")
145
-
146
- # ==========================================================
147
- # πŸ—‚οΈ DOCUMENT PREVIEW
148
- # ==========================================================
149
- if temp_path:
150
- st.markdown("---")
151
- with st.expander("πŸ“„ Document Preview", expanded=False):
152
- st.text_area("Extracted text (first 1000 chars):", text[:1000], height=180)
153
- st.caption(f"πŸ“¦ {len(chunks)} chunks processed.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # ==========================================================
2
+ # streamlit_app.py β€” Restored Centered Layout + Green Status UI
3
  # ==========================================================
4
  import os
5
  import re
 
8
  from vectorstore import build_faiss_index
9
  from qa import retrieve_chunks, generate_answer, cache_embeddings, embed_chunks, genai_generate
10
 
11
+ # βœ… Centered layout again (this caused the stretch difference)
12
+ st.set_page_config(page_title="Enterprise Knowledge Assistant", layout="centered")
13
 
14
  # ==========================================================
15
+ # 🧭 SIDEBAR β€” As before
16
  # ==========================================================
17
  with st.sidebar:
18
  st.markdown("### 🧭 Response Mode")
 
37
  st.caption("✨ Built by Shubham Sharma")
38
 
39
  # ==========================================================
40
+ # 🧠 SESSION STATE
41
  # ==========================================================
42
  for key, val in {
43
  "user_query_input": "",
 
55
  st.experimental_rerun()
56
 
57
  # ==========================================================
58
+ # πŸ“˜ PAGE HEADER (Centered)
59
  # ==========================================================
60
  st.markdown(
61
  """
62
+ <div style="text-align:center; margin-top:-10px;">
63
+ <h1>πŸ“„ Enterprise Knowledge Assistant</h1>
64
+ <p style="color:gray; font-size:15px;">
65
+ Query SAP documentation and enterprise PDFs β€” powered by reasoning and retrieval.
66
+ </p>
67
+ </div>
68
  """,
69
  unsafe_allow_html=True,
70
  )
71
 
72
  # ==========================================================
73
+ # πŸ“„ MAIN CONTAINER β€” Centered
74
  # ==========================================================
75
+ col_spacer_left, col_main, col_spacer_right = st.columns([0.15, 0.7, 0.15])
76
+ with col_main:
77
+
78
+ # ----------------------------------------------------------
79
+ # πŸ“‚ Document Upload / Selection
80
+ # ----------------------------------------------------------
81
+ st.markdown("### Select a document:")
82
+ doc_choice = st.radio("", ("-- Select --", "Sample PDF", "Upload Custom PDF"))
83
+
84
+ temp_path = None
85
+ if doc_choice == "Sample PDF":
86
+ temp_path = os.path.join(os.path.dirname(__file__), "sample.pdf")
87
+ st.success("πŸ“˜ Sample PDF loaded successfully. Ask questions below.")
88
+ st.success("βœ… Document ready β€” you can now ask questions below.")
89
+ elif doc_choice == "Upload Custom PDF":
90
+ uploaded_file = st.file_uploader("Upload your PDF", type="pdf")
91
+ if uploaded_file:
92
+ temp_path = os.path.join("/tmp", uploaded_file.name)
93
+ with open(temp_path, "wb") as f:
94
+ f.write(uploaded_file.getbuffer())
95
+ st.success(f"βœ… '{uploaded_file.name}' uploaded successfully β€” ready to query below.")
96
+ st.success("βœ… Document ready β€” you can now ask questions below.")
97
+ else:
98
+ st.info("⬅️ Please select or upload a document to begin.")
99
+
100
+ # ----------------------------------------------------------
101
+ # 🧠 Process document when loaded
102
+ # ----------------------------------------------------------
103
+ if temp_path:
104
+ text, toc = extract_text_from_pdf(temp_path)
105
+ chunks = chunk_text(text, chunk_size=chunk_size, overlap=overlap)
106
+ embeddings = cache_embeddings(os.path.basename(temp_path), chunks, embed_chunks)
107
+ index = build_faiss_index(embeddings)
108
+
109
+ # ----------------------------------------------------------
110
+ # πŸ’‘ Suggested Questions
111
+ # ----------------------------------------------------------
112
+ if not st.session_state["query_suggestions_fixed"]:
113
+ st.session_state["query_suggestions_fixed"] = [
114
+ "What is the purpose of this document?",
115
+ "How can integration be set up in SAP Cloud?",
116
+ "What are the prerequisites mentioned?",
117
+ "What steps are involved in configuration?",
118
+ "How to troubleshoot integration issues?",
119
+ "What is the key functionality covered?"
120
+ ]
121
+
122
+ st.markdown("### Ask the Assistant")
123
+
124
+ visible_qs = (
125
+ st.session_state["query_suggestions_fixed"][:3]
126
+ if not st.session_state["show_more"]
127
+ else st.session_state["query_suggestions_fixed"]
128
+ )
129
+ cols = st.columns(3)
130
+ for i, q in enumerate(visible_qs):
131
+ if cols[i % 3].button(f"πŸ’¬ {q}", key=f"suggest_{i}"):
132
+ set_user_query(q, i)
133
+
134
+ if st.button("Show more β–Ό" if not st.session_state["show_more"] else "Show less β–²"):
135
+ st.session_state["show_more"] = not st.session_state["show_more"]
136
+
137
+ # ----------------------------------------------------------
138
+ # 🧩 Query Input
139
+ # ----------------------------------------------------------
140
+ user_query = st.text_input(
141
+ "Type your question or click one above:",
142
+ value=st.session_state["user_query_input"],
143
+ key="user_query_input"
144
+ )
145
+
146
+ # ----------------------------------------------------------
147
+ # πŸ€– Generate Answer
148
+ # ----------------------------------------------------------
149
+ if user_query:
150
+ reasoning_mode = mode == "Extended (Document + general)"
151
+ st.markdown(f"**Mode:** {'🧠 Extended' if reasoning_mode else 'πŸ“„ Strict Document'}")
152
+
153
+ with st.spinner("πŸ’­ Generating answer..."):
154
+ retrieved = retrieve_chunks(
155
+ user_query, index, chunks, top_k=top_k, embeddings=embeddings
156
+ )
157
+ answer = generate_answer(
158
+ user_query, retrieved, reasoning_mode=reasoning_mode
159
+ )
160
+
161
+ st.markdown("### Assistant’s Answer")
162
+ st.markdown(
163
+ f"""
164
+ <div style='background:#0f172a;border-left:4px solid #22c55e;
165
+ padding:12px;border-radius:8px;color:#f1f5f9'>{answer}</div>
166
+ """,
167
+ unsafe_allow_html=True,
168
+ )
169
+
170
+ with st.expander("πŸ“˜ Supporting Context", expanded=False):
171
+ for i, chunk in enumerate(retrieved, 1):
172
+ st.markdown(f"**Chunk {i}:** {chunk.strip()}")
173
+
174
+ # ----------------------------------------------------------
175
+ # πŸ“‘ Document Preview
176
+ # ----------------------------------------------------------
177
+ if temp_path:
178
+ st.markdown("---")
179
+ with st.expander("πŸ“„ Document Preview", expanded=False):
180
+ st.text_area("Extracted text (first 1000 chars):", text[:1000], height=180)
181
+ st.caption(f"πŸ“¦ {len(chunks)} chunks processed.")