krishbaresha commited on
Commit
78ef436
Β·
verified Β·
1 Parent(s): f22dafb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -57
app.py CHANGED
@@ -8,6 +8,7 @@ import numpy as np
8
  import faiss
9
  from sentence_transformers import SentenceTransformer
10
  from PIL import Image
 
11
 
12
  # ---------------------------
13
  # CONFIG
@@ -15,8 +16,14 @@ from PIL import Image
15
  st.set_page_config(page_title="Krish GPT Pro", page_icon="πŸ€–", layout="wide")
16
  st.markdown("""
17
  <style>
 
18
  .chat-container { max-width: 800px; margin:auto; }
 
 
 
19
  .stButton>button { background-color: #646cff; color:white; }
 
 
20
  </style>
21
  """, unsafe_allow_html=True)
22
  st.title("πŸ€– Krish GPT Pro")
@@ -58,7 +65,7 @@ def ocr_space_image(file, api_key):
58
  return text
59
 
60
  # ---------------------------
61
- # AUTH SYSTEM (Signup/Login/Reset)
62
  # ---------------------------
63
  if "user" not in st.session_state:
64
  st.session_state.user = None
@@ -103,46 +110,21 @@ elif auth_choice == "Anonymous":
103
  st.sidebar.info("You are using the app anonymously. History will not be saved.")
104
 
105
  # ---------------------------
106
- # FILE UPLOAD & TEXT EXTRACTION
107
- # ---------------------------
108
- uploaded_file = st.file_uploader("πŸ“„ Upload PDF / πŸ–ΌοΈ Image", type=["pdf","png","jpg","jpeg"])
109
- file_text = ""
110
-
111
- if uploaded_file:
112
- if uploaded_file.type == "application/pdf":
113
- reader = PdfReader(uploaded_file)
114
- for page in reader.pages:
115
- t = page.extract_text()
116
- if t:
117
- file_text += t
118
- elif "image" in uploaded_file.type:
119
- file_text = ocr_space_image(uploaded_file, OCR_API_KEY)
120
-
121
- # ---------------------------
122
- # CHUNK + FAISS
123
  # ---------------------------
124
- def chunk_text(text, chunk_size=500):
125
- return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
126
-
127
- def build_index(chunks):
128
- embeddings = embedder.encode(chunks)
129
- dim = embeddings.shape[1]
130
- index = faiss.IndexFlatL2(dim)
131
- index.add(np.array(embeddings))
132
- return index, embeddings
133
-
134
- def search(query, chunks, index):
135
- q_emb = embedder.encode([query])
136
- D, I = index.search(np.array(q_emb), k=min(3,len(chunks)))
137
- return "\n".join([chunks[i] for i in I[0]])
138
 
139
- if uploaded_file and file_text:
140
- chunks = chunk_text(file_text)
141
- index, embeddings = build_index(chunks)
142
- st.session_state.rag_data = (chunks, index)
 
 
 
143
 
144
  # ---------------------------
145
- # CHAT FUNCTIONS
146
  # ---------------------------
147
  def save_chat(user_id, role, content):
148
  supabase.table("chats").insert({
@@ -155,32 +137,71 @@ def load_chat(user_id):
155
  data = supabase.table("chats").select("*").eq("user_id", user_id).order("created_at").execute()
156
  return data.data
157
 
158
- # ---------------------------
159
- # SESSION STATE
160
- # ---------------------------
161
- if "messages" not in st.session_state:
162
- st.session_state.messages = []
163
-
164
  # Load chat history if registered
165
- if st.session_state.user:
166
- chat_history = load_chat(st.session_state.user.id)
167
  for msg in chat_history:
168
- st.chat_message(msg["role"]).write(msg["content"])
169
  st.session_state.messages.append({"role": msg["role"], "content": msg["content"]})
170
 
171
  # ---------------------------
172
- # USER INPUT
173
  # ---------------------------
174
- prompt = st.chat_input("πŸ’¬ Ask anything...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
  if prompt:
177
  st.session_state.messages.append({"role":"user","content":prompt})
178
- st.chat_message("user").write(prompt)
 
179
  context = ""
180
- if "rag_data" in st.session_state:
181
  chunks, index = st.session_state.rag_data
182
- context = search(prompt, chunks, index)
183
- with st.chat_message("assistant"):
 
 
 
184
  try:
185
  response = client.chat.completions.create(
186
  model="llama-3.3-70b-versatile",
@@ -191,8 +212,10 @@ if prompt:
191
  reply = response.choices[0].message.content
192
  except Exception as e:
193
  reply = f"❌ Error: {str(e)}"
194
- st.write(reply)
195
- st.session_state.messages.append({"role":"assistant","content":reply})
196
- if st.session_state.user:
197
- save_chat(st.session_state.user.id,"user",prompt)
198
- save_chat(st.session_state.user.id,"assistant",reply)
 
 
 
8
  import faiss
9
  from sentence_transformers import SentenceTransformer
10
  from PIL import Image
11
+ import io
12
 
13
  # ---------------------------
14
  # CONFIG
 
16
  st.set_page_config(page_title="Krish GPT Pro", page_icon="πŸ€–", layout="wide")
17
  st.markdown("""
18
  <style>
19
+ /* Chat bubbles */
20
  .chat-container { max-width: 800px; margin:auto; }
21
+ .chat-bubble { padding: 12px; border-radius: 12px; margin-bottom: 8px; max-width: 80%; }
22
+ .user { background-color:#646cff; color:white; margin-left:auto; text-align:right; }
23
+ .assistant { background-color:#f1f0f0; color:black; margin-right:auto; text-align:left; }
24
  .stButton>button { background-color: #646cff; color:white; }
25
+ .upload-btn { display:flex; align-items:center; gap:5px; cursor:pointer; padding:5px 10px; border:1px solid #ccc; border-radius:5px; }
26
+ .upload-btn:hover { background-color:#f5f5f5; }
27
  </style>
28
  """, unsafe_allow_html=True)
29
  st.title("πŸ€– Krish GPT Pro")
 
65
  return text
66
 
67
  # ---------------------------
68
+ # AUTH SYSTEM
69
  # ---------------------------
70
  if "user" not in st.session_state:
71
  st.session_state.user = None
 
110
  st.sidebar.info("You are using the app anonymously. History will not be saved.")
111
 
112
  # ---------------------------
113
+ # SESSION STATE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  # ---------------------------
115
+ if "messages" not in st.session_state:
116
+ st.session_state.messages = []
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ # Get current user safely
119
+ current_user_resp = supabase.auth.get_user()
120
+ if current_user_resp and current_user_resp.user:
121
+ user = current_user_resp.user
122
+ else:
123
+ user = st.session_state.user # fallback to session_state
124
+ st.session_state.user = user
125
 
126
  # ---------------------------
127
+ # CHAT HISTORY FUNCTIONS
128
  # ---------------------------
129
  def save_chat(user_id, role, content):
130
  supabase.table("chats").insert({
 
137
  data = supabase.table("chats").select("*").eq("user_id", user_id).order("created_at").execute()
138
  return data.data
139
 
 
 
 
 
 
 
140
  # Load chat history if registered
141
+ if user:
142
+ chat_history = load_chat(user.id)
143
  for msg in chat_history:
144
+ st.markdown(f'<div class="chat-bubble {msg["role"]}">{msg["content"]}</div>', unsafe_allow_html=True)
145
  st.session_state.messages.append({"role": msg["role"], "content": msg["content"]})
146
 
147
  # ---------------------------
148
+ # FILE UPLOAD + RAG
149
  # ---------------------------
150
+ if "rag_data" not in st.session_state:
151
+ st.session_state.rag_data = None
152
+
153
+ uploaded_file = st.file_uploader("πŸ“Ž Upload PDF/Image", type=["pdf","png","jpg","jpeg"], key="file_upload")
154
+ file_text = ""
155
+
156
+ if uploaded_file:
157
+ if uploaded_file.type == "application/pdf":
158
+ reader = PdfReader(uploaded_file)
159
+ for page in reader.pages:
160
+ t = page.extract_text()
161
+ if t:
162
+ file_text += t
163
+ elif "image" in uploaded_file.type:
164
+ file_text = ocr_space_image(uploaded_file, OCR_API_KEY)
165
+
166
+ if file_text:
167
+ # Chunk + FAISS
168
+ def chunk_text(text, chunk_size=500):
169
+ return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
170
+ def build_index(chunks):
171
+ embeddings = embedder.encode(chunks)
172
+ dim = embeddings.shape[1]
173
+ index = faiss.IndexFlatL2(dim)
174
+ index.add(np.array(embeddings))
175
+ return index, embeddings
176
+ def search(query, chunks, index):
177
+ q_emb = embedder.encode([query])
178
+ D, I = index.search(np.array(q_emb), k=min(3,len(chunks)))
179
+ return "\n".join([chunks[i] for i in I[0]])
180
+
181
+ chunks = chunk_text(file_text)
182
+ index, embeddings = build_index(chunks)
183
+ st.session_state.rag_data = (chunks, index)
184
+
185
+ # Show uploaded file inside chat
186
+ st.markdown(f'<div class="chat-bubble assistant">πŸ“Ž Uploaded file processed successfully!</div>', unsafe_allow_html=True)
187
+
188
+ # ---------------------------
189
+ # CHAT INPUT
190
+ # ---------------------------
191
+ prompt = st.chat_input("πŸ’¬ Type your message...")
192
 
193
  if prompt:
194
  st.session_state.messages.append({"role":"user","content":prompt})
195
+ st.markdown(f'<div class="chat-bubble user">{prompt}</div>', unsafe_allow_html=True)
196
+
197
  context = ""
198
+ if st.session_state.rag_data:
199
  chunks, index = st.session_state.rag_data
200
+ q_emb = embedder.encode([prompt])
201
+ D, I = index.search(np.array(q_emb), k=min(3,len(chunks)))
202
+ context = "\n".join([chunks[i] for i in I[0]])
203
+
204
+ with st.spinner("πŸ€– Krish GPT Pro is thinking..."):
205
  try:
206
  response = client.chat.completions.create(
207
  model="llama-3.3-70b-versatile",
 
212
  reply = response.choices[0].message.content
213
  except Exception as e:
214
  reply = f"❌ Error: {str(e)}"
215
+
216
+ st.session_state.messages.append({"role":"assistant","content":reply})
217
+ st.markdown(f'<div class="chat-bubble assistant">{reply}</div>', unsafe_allow_html=True)
218
+
219
+ if user:
220
+ save_chat(user.id,"user",prompt)
221
+ save_chat(user.id,"assistant",reply)