jasvir-singh1021 commited on
Commit
3d4310e
Β·
verified Β·
1 Parent(s): 29a3cbd

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +73 -32
src/streamlit_app.py CHANGED
@@ -1,74 +1,115 @@
1
  import streamlit as st
2
  import json
3
- from io import StringIO
4
 
5
- # Configure page
6
- st.set_page_config(page_title="Document Parser", layout="wide")
7
 
8
- # Session state for conversation history
9
  if "conversation" not in st.session_state:
10
  st.session_state.conversation = []
 
 
11
 
12
- # Sidebar: API key + temperature
13
  with st.sidebar:
14
  st.title("βš™οΈ Settings")
15
- api_key = st.text_input("πŸ”‘ OpenAI API Key", type="password")
16
- temperature = st.slider("πŸ”₯ Model Temperature", 0.0, 1.0, 0.0, 0.1)
 
 
17
 
18
- # Main header
19
  st.title("πŸ“„ Document Parser")
20
- st.markdown("Upload documents and chat with a GPT-4 powered assistant.")
21
 
22
- # Upload documents
23
  uploaded_files = st.file_uploader(
24
  "πŸ“€ Upload Documents (PDF, DOCX, TXT, etc.)",
25
  type=["pdf", "docx", "doc", "txt", "rtf", "html"],
26
  accept_multiple_files=True
27
  )
28
 
 
29
  if uploaded_files:
30
  st.success(f"{len(uploaded_files)} document(s) uploaded.")
 
 
 
 
31
  else:
32
- st.info("Please upload at least one document to continue.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- # Input for user question
35
- question = st.text_input("πŸ’¬ Ask a question about your documents:")
 
 
 
 
36
 
37
- # Send button
38
- if st.button("πŸš€ Ask") and question and uploaded_files and api_key:
39
- with st.spinner("Processing..."):
40
- # Here you'd pass files + question + temperature + API key to your backend
41
- # Replace this with real logic (e.g., LlamaIndex + OpenAI)
42
- mock_answer = f"🧠 Based on the uploaded documents, here's a mock answer to: '{question}'"
43
 
44
- # Add to conversation history
45
- st.session_state.conversation.append({"role": "user", "content": question})
46
- st.session_state.conversation.append({"role": "assistant", "content": mock_answer})
47
 
48
- # Display conversation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  if st.session_state.conversation:
50
- st.markdown("## 🧾 Conversation")
51
  for msg in st.session_state.conversation:
52
- if msg["role"] == "user":
53
- st.markdown(f"**You:** {msg['content']}")
54
- else:
55
- st.markdown(f"**Assistant:** {msg['content']}")
56
 
 
57
  st.markdown("---")
58
-
59
- # Download buttons
60
  col1, col2 = st.columns(2)
61
 
62
  with col1:
63
  if st.button("πŸ—‘οΈ Clear Conversation"):
64
  st.session_state.conversation = []
 
65
  st.experimental_rerun()
66
 
67
  with col2:
68
  format = st.selectbox("Download Format", ["TXT", "JSON"])
69
  if format == "TXT":
70
  content = "\n\n".join(
71
- f"{msg['role'].capitalize()}:\n{msg['content']}" for msg in st.session_state.conversation
 
72
  )
73
  mime = "text/plain"
74
  filename = "conversation.txt"
@@ -77,4 +118,4 @@ if st.session_state.conversation:
77
  mime = "application/json"
78
  filename = "conversation.json"
79
 
80
- st.download_button("πŸ“₯ Download", content, filename=filename, mime=mime)
 
1
  import streamlit as st
2
  import json
3
+ from datetime import datetime
4
 
5
+ # Page config
6
+ st.set_page_config(page_title="Document Parser", layout="wide", page_icon="πŸ“„")
7
 
8
+ # Initialize state
9
  if "conversation" not in st.session_state:
10
  st.session_state.conversation = []
11
+ if "last_question" not in st.session_state:
12
+ st.session_state.last_question = None
13
 
14
+ # Sidebar settings
15
  with st.sidebar:
16
  st.title("βš™οΈ Settings")
17
+ api_key = st.text_input("πŸ”‘ OpenAI API Key", type="password", help="Paste your OpenAI API key")
18
+ temperature = st.slider("πŸ”₯ Model Temperature", 0.0, 1.0, 0.3, 0.05, help="Higher values make responses more creative.")
19
+ st.markdown("---")
20
+ st.caption("Built with ❀️ using Streamlit")
21
 
22
+ # Title & instructions
23
  st.title("πŸ“„ Document Parser")
24
+ st.markdown("Upload your documents and ask questions powered by GPT-4 and LlamaIndex (or mock engine).")
25
 
26
+ # File upload
27
  uploaded_files = st.file_uploader(
28
  "πŸ“€ Upload Documents (PDF, DOCX, TXT, etc.)",
29
  type=["pdf", "docx", "doc", "txt", "rtf", "html"],
30
  accept_multiple_files=True
31
  )
32
 
33
+ # File display
34
  if uploaded_files:
35
  st.success(f"{len(uploaded_files)} document(s) uploaded.")
36
+ with st.expander("πŸ“š Uploaded Files Overview"):
37
+ for file in uploaded_files:
38
+ st.write(f"β€’ `{file.name}` ({round(file.size / 1024, 2)} KB)")
39
+ st.markdown("βœ… Ready to ask questions.")
40
  else:
41
+ st.warning("⚠️ Please upload at least one document.")
42
+
43
+ # Suggestive prompts
44
+ if uploaded_files:
45
+ st.markdown("#### πŸ’‘ Suggested Questions")
46
+ suggestions = [
47
+ "What is the main topic of the documents?",
48
+ "Summarize the contents.",
49
+ "Are there any deadlines or dates mentioned?",
50
+ "What are the key takeaways?"
51
+ ]
52
+ for i, s in enumerate(suggestions):
53
+ if st.button(f"πŸ’¬ {s}", key=f"suggestion_{i}"):
54
+ st.session_state.last_question = s
55
+
56
+ # Text input
57
+ question = st.text_input("πŸ”Ž Ask a question about your documents:", value=st.session_state.last_question or "")
58
 
59
+ # Ask button
60
+ ask_col, retry_col = st.columns([4, 1])
61
+ with ask_col:
62
+ send = st.button("πŸš€ Ask")
63
+ with retry_col:
64
+ retry = st.button("πŸ” Retry")
65
 
66
+ if (send or retry) and question and api_key and uploaded_files:
67
+ st.session_state.last_question = question
68
+ with st.spinner("Analyzing your documents..."):
69
+ # TODO: Replace this with actual LLM logic
70
+ mock_answer = f"πŸ€– Here's a simulated response to your question: **'{question}'**"
 
71
 
72
+ # Tag this session
73
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
74
 
75
+ # Store in conversation
76
+ st.session_state.conversation.append({
77
+ "role": "user",
78
+ "content": question,
79
+ "timestamp": timestamp
80
+ })
81
+ st.session_state.conversation.append({
82
+ "role": "assistant",
83
+ "content": mock_answer,
84
+ "timestamp": timestamp
85
+ })
86
+
87
+ elif send or retry:
88
+ st.error("Please make sure you've uploaded documents and provided an API key.")
89
+
90
+ # Conversation history
91
  if st.session_state.conversation:
92
+ st.markdown("## 🧾 Conversation History")
93
  for msg in st.session_state.conversation:
94
+ author = "πŸ§‘ You" if msg["role"] == "user" else "πŸ€– Assistant"
95
+ st.markdown(f"**{author}** *(at {msg['timestamp']})*:\n\n{msg['content']}", unsafe_allow_html=True)
 
 
96
 
97
+ # Actions
98
  st.markdown("---")
 
 
99
  col1, col2 = st.columns(2)
100
 
101
  with col1:
102
  if st.button("πŸ—‘οΈ Clear Conversation"):
103
  st.session_state.conversation = []
104
+ st.session_state.last_question = None
105
  st.experimental_rerun()
106
 
107
  with col2:
108
  format = st.selectbox("Download Format", ["TXT", "JSON"])
109
  if format == "TXT":
110
  content = "\n\n".join(
111
+ f"{msg['role'].capitalize()} ({msg['timestamp']}):\n{msg['content']}"
112
+ for msg in st.session_state.conversation
113
  )
114
  mime = "text/plain"
115
  filename = "conversation.txt"
 
118
  mime = "application/json"
119
  filename = "conversation.json"
120
 
121
+ st.download_button("πŸ“₯ Download", content, file_name=filename, mime=mime)