ahmedumeraziz commited on
Commit
02ebc7d
Β·
verified Β·
1 Parent(s): 0dfdd0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -32
app.py CHANGED
@@ -1,19 +1,37 @@
1
  import streamlit as st
2
- from utils.auth import authenticate, generate_token, verify_token
 
3
  from utils.database import initialize_vector_db, add_to_collection
4
  from utils.rag_utils import process_pdf, get_groq_response
5
- import os
6
 
7
- # Configure for HF Spaces
8
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
9
 
10
- # Initialize FAISS DB
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  if 'vector_db' not in st.session_state:
12
- st.session_state.vector_db = initialize_vector_db()
 
 
 
 
13
 
14
- # Authentication
15
  def login_section():
16
- st.sidebar.title("πŸ” Groq RAG Login")
17
  username = st.sidebar.text_input("Username")
18
  password = st.sidebar.text_input("Password", type="password")
19
 
@@ -21,38 +39,88 @@ def login_section():
21
  if authenticate(username, password):
22
  st.session_state.token = generate_token(username)
23
  st.session_state.logged_in = True
24
- st.sidebar.success("Logged in!")
25
  st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- # Main App
28
  def main_app():
29
  st.title("⚑ Groq-Powered RAG Chatbot")
 
30
 
31
- # PDF Upload
32
- uploaded_file = st.file_uploader("Upload PDF", type="pdf")
33
- if uploaded_file:
34
- with st.spinner("Extracting text..."):
35
- chunks = process_pdf(uploaded_file)
36
- if add_to_collection(chunks):
37
- st.success(f"Added {len(chunks)} chunks to knowledge base!")
38
-
39
- # Chat
40
- if prompt := st.chat_input("Ask about your PDFs"):
41
- with st.spinner("Generating answer (Groq speed!)..."):
42
- response = get_groq_response(prompt, st.session_state.vector_db)
43
- st.chat_message("user").write(prompt)
44
- st.chat_message("assistant").write(response)
45
-
46
- # Auth flow
47
- if not st.session_state.get("logged_in", False):
48
  login_section()
49
  else:
50
- if verify_token(st.session_state.token):
 
 
 
 
51
  main_app()
52
- if st.sidebar.button("Logout"):
53
  st.session_state.clear()
54
  st.rerun()
55
- else:
56
- st.error("Session expired")
57
- st.session_state.clear()
58
- login_section()
 
 
 
 
 
 
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
7
 
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
 
 
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
+
70
+ for message in st.session_state.messages:
71
+ with st.chat_message(message["role"]):
72
+ st.markdown(message["content"])
73
+
74
+ if prompt := st.chat_input("Ask about your documents"):
75
+ st.session_state.messages.append({"role": "user", "content": prompt})
76
+ with st.chat_message("user"):
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")
111
+ st.session_state.logged_in = False
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
+ """)