ahmedumeraziz commited on
Commit
3c55bc5
Β·
verified Β·
1 Parent(s): 02ebc7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -53
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import streamlit as st
2
  import os
3
- import sys
4
  from utils.database import initialize_vector_db, add_to_collection
5
  from utils.rag_utils import process_pdf, get_groq_response
6
  from typing import Optional
@@ -8,62 +7,38 @@ from typing import Optional
8
  # Configure environment
9
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
10
 
11
- # ---- Authentication Setup with Fallback ----
12
  try:
13
  from utils.auth import authenticate, generate_token, verify_token
14
  AUTH_ENABLED = True
15
  except ImportError as e:
16
- st.warning(f"Authentication disabled due to: {str(e)}")
17
  AUTH_ENABLED = False
18
 
19
- # Fallback dummy auth functions
20
  def authenticate(*args, **kwargs): return True
21
  def generate_token(*args, **kwargs): return "dummy_token"
22
  def verify_token(*args, **kwargs): return True
23
 
24
- # ---- Session State Initialization ----
25
  if 'vector_db' not in st.session_state:
26
- with st.spinner("πŸ”„ Initializing AI system..."):
27
  st.session_state.vector_db = initialize_vector_db()
28
 
29
- if 'logged_in' not in st.session_state:
30
- st.session_state.logged_in = False if AUTH_ENABLED else True
31
-
32
- # ---- UI Components ----
33
- def login_section():
34
- st.sidebar.title("πŸ” Admin Login")
35
- username = st.sidebar.text_input("Username")
36
- password = st.sidebar.text_input("Password", type="password")
37
-
38
- if st.sidebar.button("Login"):
39
- if authenticate(username, password):
40
- st.session_state.token = generate_token(username)
41
- st.session_state.logged_in = True
42
- st.sidebar.success("Login successful!")
43
- st.rerun()
44
- else:
45
- st.sidebar.error("Invalid credentials")
46
-
47
- def pdf_uploader():
48
- st.subheader("πŸ“€ Upload PDF Documents")
49
- uploaded_file = st.file_uploader(
50
- "Choose a PDF file",
51
- type="pdf",
52
- label_visibility="collapsed"
53
- )
54
-
55
  if uploaded_file:
56
- with st.spinner("πŸ” Extracting knowledge from PDF..."):
57
  try:
58
  chunks = process_pdf(uploaded_file)
59
  if add_to_collection(chunks):
60
- st.success(f"βœ… Processed {len(chunks)} text chunks!")
61
  except Exception as e:
62
- st.error(f"PDF processing failed: {str(e)}")
63
 
64
- def chat_interface():
65
- st.subheader("πŸ’¬ Chat with Your Documents")
66
-
67
  if "messages" not in st.session_state:
68
  st.session_state.messages = []
69
 
@@ -77,34 +52,49 @@ def chat_interface():
77
  st.markdown(prompt)
78
 
79
  with st.chat_message("assistant"):
80
- with st.spinner("πŸ€” Thinking..."):
81
  try:
82
- response = get_groq_response(prompt, st.session_state.vector_db)
 
 
 
 
 
83
  st.markdown(response)
84
  st.session_state.messages.append({"role": "assistant", "content": response})
85
  except Exception as e:
86
- st.error(f"Error generating response: {str(e)}")
87
 
88
- # ---- Main App Flow ----
89
  def main_app():
90
  st.title("⚑ Groq-Powered RAG Chatbot")
91
- st.caption("Upload PDFs and ask questions with lightning-fast responses")
92
 
93
- tab1, tab2 = st.tabs(["πŸ“„ Documents", "πŸ’¬ Chat"])
94
 
95
  with tab1:
96
- pdf_uploader()
97
 
98
  with tab2:
99
- chat_interface()
100
 
101
- if st.sidebar.button("πŸ”„ Reset Chat"):
102
  st.session_state.messages = []
103
  st.rerun()
104
 
105
  # ---- Authentication Flow ----
106
- if AUTH_ENABLED and not st.session_state.logged_in:
107
- login_section()
 
 
 
 
 
 
 
 
 
 
 
108
  else:
109
  if AUTH_ENABLED and not verify_token(st.session_state.get("token", "")):
110
  st.error("Session expired")
@@ -112,15 +102,14 @@ else:
112
  st.rerun()
113
  else:
114
  main_app()
115
- if AUTH_ENABLED and st.sidebar.button("πŸšͺ Logout"):
116
  st.session_state.clear()
117
  st.rerun()
118
 
119
  # ---- Footer ----
120
  st.sidebar.markdown("---")
121
  st.sidebar.markdown("""
122
- **Technical Stack:**
123
- - Groq Cloud (Mixtral 8x7b)
124
  - FAISS Vector Store
125
- - Streamlit UI
126
  """)
 
1
  import streamlit as st
2
  import os
 
3
  from utils.database import initialize_vector_db, add_to_collection
4
  from utils.rag_utils import process_pdf, get_groq_response
5
  from typing import Optional
 
7
  # Configure environment
8
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
9
 
10
+ # ---- Authentication Setup ----
11
  try:
12
  from utils.auth import authenticate, generate_token, verify_token
13
  AUTH_ENABLED = True
14
  except ImportError as e:
15
+ st.warning(f"Authentication disabled: {str(e)}")
16
  AUTH_ENABLED = False
17
 
18
+ # Fallback auth functions
19
  def authenticate(*args, **kwargs): return True
20
  def generate_token(*args, **kwargs): return "dummy_token"
21
  def verify_token(*args, **kwargs): return True
22
 
23
+ # ---- Initialize Vector DB ----
24
  if 'vector_db' not in st.session_state:
25
+ with st.spinner("Initializing AI system..."):
26
  st.session_state.vector_db = initialize_vector_db()
27
 
28
+ # ---- PDF Processing Section ----
29
+ def handle_pdf_upload():
30
+ uploaded_file = st.file_uploader("Upload PDF", type="pdf")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  if uploaded_file:
32
+ with st.spinner("Processing PDF..."):
33
  try:
34
  chunks = process_pdf(uploaded_file)
35
  if add_to_collection(chunks):
36
+ st.success(f"Processed {len(chunks)} text chunks!")
37
  except Exception as e:
38
+ st.error(f"PDF processing error: {str(e)}")
39
 
40
+ # ---- Chat Interface ----
41
+ def handle_chat():
 
42
  if "messages" not in st.session_state:
43
  st.session_state.messages = []
44
 
 
52
  st.markdown(prompt)
53
 
54
  with st.chat_message("assistant"):
55
+ with st.spinner("Generating response..."):
56
  try:
57
+ # Updated to use current Groq model
58
+ response = get_groq_response(
59
+ prompt,
60
+ st.session_state.vector_db,
61
+ model_name="mixtral-8x7b-32768" # Updated model name
62
+ )
63
  st.markdown(response)
64
  st.session_state.messages.append({"role": "assistant", "content": response})
65
  except Exception as e:
66
+ st.error(f"Chat error: {str(e)}")
67
 
68
+ # ---- Main App ----
69
  def main_app():
70
  st.title("⚑ Groq-Powered RAG Chatbot")
 
71
 
72
+ tab1, tab2 = st.tabs(["Documents", "Chat"])
73
 
74
  with tab1:
75
+ handle_pdf_upload()
76
 
77
  with tab2:
78
+ handle_chat()
79
 
80
+ if st.sidebar.button("Reset Chat"):
81
  st.session_state.messages = []
82
  st.rerun()
83
 
84
  # ---- Authentication Flow ----
85
+ if AUTH_ENABLED and not st.session_state.get("logged_in", False):
86
+ st.sidebar.title("Login")
87
+ username = st.sidebar.text_input("Username")
88
+ password = st.sidebar.text_input("Password", type="password")
89
+
90
+ if st.sidebar.button("Login"):
91
+ if authenticate(username, password):
92
+ st.session_state.logged_in = True
93
+ st.session_state.token = generate_token(username)
94
+ st.sidebar.success("Logged in!")
95
+ st.rerun()
96
+ else:
97
+ st.sidebar.error("Invalid credentials")
98
  else:
99
  if AUTH_ENABLED and not verify_token(st.session_state.get("token", "")):
100
  st.error("Session expired")
 
102
  st.rerun()
103
  else:
104
  main_app()
105
+ if AUTH_ENABLED and st.sidebar.button("Logout"):
106
  st.session_state.clear()
107
  st.rerun()
108
 
109
  # ---- Footer ----
110
  st.sidebar.markdown("---")
111
  st.sidebar.markdown("""
112
+ **Using:**
113
+ - Groq Cloud (Mixtral)
114
  - FAISS Vector Store
 
115
  """)