Tesneem commited on
Commit
f8d2230
·
verified ·
1 Parent(s): c7c0d2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -21
app.py CHANGED
@@ -1,17 +1,18 @@
1
  import os
2
  import streamlit as st
3
  import tempfile
4
- from pymongo import MongoClient
5
  from datetime import datetime
6
  from pathlib import Path
7
- from document_chunker import DocumentChunker
8
  from urllib.parse import quote_plus
 
9
 
10
  # === MongoDB connection via Hugging Face secrets ===
11
  user = quote_plus(os.getenv("MONGO_USER"))
12
  password = quote_plus(os.getenv("MONGO_PASS"))
13
  cluster = os.getenv("MONGO_CLUSTER")
14
  db_name = os.environ.get("MONGO_DB", "grant_docs")
 
15
  mongo_uri = f"mongodb+srv://{user}:{password}@{cluster}/{db_name}?retryWrites=true&w=majority&tls=true&tlsAllowInvalidCertificates=true"
16
  client = MongoClient(mongo_uri, tls=True, tlsAllowInvalidCertificates=True, serverSelectionTimeoutMS=20000)
17
  db = client[db_name]
@@ -22,12 +23,11 @@ st.title("📄 Document Chunker & Uploader")
22
 
23
  with st.sidebar:
24
  st.header("Settings")
25
-
26
- # Fetch collection names for dropdown
27
  try:
28
  existing_collections = db.list_collection_names()
29
  existing_collections.append("Create New Collection")
30
- selected_collection = st.selectbox("Choose MongoDB Collection", existing_collections, index=existing_collections.index("doc_chunks_cat") if "doc_chunks_cat" in existing_collections else 0)
 
31
  except Exception as e:
32
  st.error(f"Failed to list collections: {e}")
33
  selected_collection = "doc_chunks_cat"
@@ -42,33 +42,46 @@ with st.sidebar:
42
 
43
  uploaded_file = st.file_uploader("Upload a DOCX, TXT, or PDF file", type=["docx", "txt", "pdf"])
44
 
45
- if uploaded_file:
 
46
  temp_path = Path(tempfile.gettempdir()) / uploaded_file.name
47
  with open(temp_path, "wb") as f:
48
  f.write(uploaded_file.getbuffer())
49
 
50
- st.success(f"Uploaded `{uploaded_file.name}`")
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- modified_time = datetime.now().isoformat()
53
- collection = db[selected_collection]
54
 
55
- if collection.find_one({"metadata.title": uploaded_file.name}):
56
  st.warning("⚠️ This file already exists in the collection. Skipping...")
57
  else:
58
  st.write("⏳ Processing with DocumentChunker...")
59
  chunker = DocumentChunker()
60
- chunks = chunker.process_document(str(temp_path))
61
 
62
  if chunks:
63
  for chunk in chunks:
64
  chunk['metadata'].update({
65
- "title": uploaded_file.name,
66
- "uploaded_at": modified_time,
67
  "is_grant_app": is_grant_app,
68
  })
69
  collection.insert_one(chunk)
70
 
71
- st.success(f"✅ {len(chunks)} chunks inserted into `{selected_collection}`")
72
 
73
  for i, c in enumerate(chunks[:3]):
74
  st.subheader(f"Chunk {i+1}: {c['metadata'].get('header') or 'No Header'}")
@@ -78,14 +91,16 @@ if uploaded_file:
78
 
79
  if len(chunks) > 3:
80
  st.info(f"... and {len(chunks)-3} more chunks processed.")
81
-
82
  else:
83
  st.warning("⚠️ No chunks were generated.")
84
 
85
- try:
86
- if temp_path.exists():
87
- os.remove(temp_path)
88
- except Exception as e:
89
- st.warning(f"⚠️ Could not delete temp file: {e}")
90
 
91
- st.rerun()
 
 
 
 
1
  import os
2
  import streamlit as st
3
  import tempfile
 
4
  from datetime import datetime
5
  from pathlib import Path
6
+ from pymongo import MongoClient
7
  from urllib.parse import quote_plus
8
+ from document_chunker import DocumentChunker
9
 
10
  # === MongoDB connection via Hugging Face secrets ===
11
  user = quote_plus(os.getenv("MONGO_USER"))
12
  password = quote_plus(os.getenv("MONGO_PASS"))
13
  cluster = os.getenv("MONGO_CLUSTER")
14
  db_name = os.environ.get("MONGO_DB", "grant_docs")
15
+
16
  mongo_uri = f"mongodb+srv://{user}:{password}@{cluster}/{db_name}?retryWrites=true&w=majority&tls=true&tlsAllowInvalidCertificates=true"
17
  client = MongoClient(mongo_uri, tls=True, tlsAllowInvalidCertificates=True, serverSelectionTimeoutMS=20000)
18
  db = client[db_name]
 
23
 
24
  with st.sidebar:
25
  st.header("Settings")
 
 
26
  try:
27
  existing_collections = db.list_collection_names()
28
  existing_collections.append("Create New Collection")
29
+ default_index = existing_collections.index("doc_chunks_cat") if "doc_chunks_cat" in existing_collections else 0
30
+ selected_collection = st.selectbox("Choose MongoDB Collection", existing_collections, index=default_index)
31
  except Exception as e:
32
  st.error(f"Failed to list collections: {e}")
33
  selected_collection = "doc_chunks_cat"
 
42
 
43
  uploaded_file = st.file_uploader("Upload a DOCX, TXT, or PDF file", type=["docx", "txt", "pdf"])
44
 
45
+ # === Store session state after upload ===
46
+ if uploaded_file and "ready_to_process" not in st.session_state:
47
  temp_path = Path(tempfile.gettempdir()) / uploaded_file.name
48
  with open(temp_path, "wb") as f:
49
  f.write(uploaded_file.getbuffer())
50
 
51
+ st.session_state["uploaded_file_name"] = uploaded_file.name
52
+ st.session_state["collection_name"] = selected_collection
53
+ st.session_state["is_grant_app"] = is_grant_app
54
+ st.session_state["temp_path"] = str(temp_path)
55
+ st.session_state["ready_to_process"] = True
56
+ st.rerun()
57
+
58
+ # === Process document ===
59
+ if st.session_state.get("ready_to_process"):
60
+ file_name = st.session_state["uploaded_file_name"]
61
+ collection_name = st.session_state["collection_name"]
62
+ is_grant_app = st.session_state["is_grant_app"]
63
+ temp_path = st.session_state["temp_path"]
64
 
65
+ st.success(f"Uploaded `{file_name}`")
66
+ collection = db[collection_name]
67
 
68
+ if collection.find_one({"metadata.title": file_name}):
69
  st.warning("⚠️ This file already exists in the collection. Skipping...")
70
  else:
71
  st.write("⏳ Processing with DocumentChunker...")
72
  chunker = DocumentChunker()
73
+ chunks = chunker.process_document(temp_path)
74
 
75
  if chunks:
76
  for chunk in chunks:
77
  chunk['metadata'].update({
78
+ "title": file_name,
79
+ "uploaded_at": datetime.now().isoformat(),
80
  "is_grant_app": is_grant_app,
81
  })
82
  collection.insert_one(chunk)
83
 
84
+ st.success(f"✅ {len(chunks)} chunks inserted into `{collection_name}`")
85
 
86
  for i, c in enumerate(chunks[:3]):
87
  st.subheader(f"Chunk {i+1}: {c['metadata'].get('header') or 'No Header'}")
 
91
 
92
  if len(chunks) > 3:
93
  st.info(f"... and {len(chunks)-3} more chunks processed.")
 
94
  else:
95
  st.warning("⚠️ No chunks were generated.")
96
 
97
+ # Clean up
98
+ try:
99
+ os.remove(temp_path)
100
+ except Exception as e:
101
+ st.warning(f"⚠️ Could not delete temp file: {e}")
102
 
103
+ # Reset session
104
+ for key in ["uploaded_file_name", "collection_name", "is_grant_app", "temp_path", "ready_to_process"]:
105
+ st.session_state.pop(key, None)
106
+ st.rerun()