Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,84 +1,84 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
from PyPDF2 import PdfReader
|
3 |
-
from langchain.vectorstores.cassandra import Cassandra
|
4 |
-
from langchain.indexes.vectorstore import VectorStoreIndexWrapper
|
5 |
-
from langchain.embeddings import HuggingFaceEmbeddings
|
6 |
-
from langchain.llms import HuggingFaceHub
|
7 |
-
from langchain.text_splitter import CharacterTextSplitter
|
8 |
-
import cassio
|
9 |
-
from dotenv import load_dotenv
|
10 |
-
import os
|
11 |
-
|
12 |
-
load_dotenv()
|
13 |
-
|
14 |
-
ASTRA_DB_APPLICATION_TOKEN = os.getenv("ASTRA_DB_APPLICATION_TOKEN")
|
15 |
-
ASTRA_DB_ID = os.getenv("ASTRA_DB_ID")
|
16 |
-
HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
17 |
-
|
18 |
-
# === Streamlit UI Setup ===
|
19 |
-
st.set_page_config(page_title="Query PDF with Free Hugging Face Models", layout="wide")
|
20 |
-
st.title("ππ¬ Query PDF using LangChain + AstraDB (Free Hugging Face Models)")
|
21 |
-
|
22 |
-
# === File Upload ===
|
23 |
-
uploaded_file = st.file_uploader("Upload your PDF", type=["pdf"])
|
24 |
-
|
25 |
-
if uploaded_file:
|
26 |
-
st.success("β
PDF uploaded successfully!")
|
27 |
-
process_button = st.button("π Process PDF")
|
28 |
-
|
29 |
-
if process_button:
|
30 |
-
# Initialize AstraDB
|
31 |
-
cassio.init(token=ASTRA_DB_APPLICATION_TOKEN, database_id=ASTRA_DB_ID)
|
32 |
-
|
33 |
-
# Read PDF contents
|
34 |
-
pdf_reader = PdfReader(uploaded_file)
|
35 |
-
raw_text = ""
|
36 |
-
for page in pdf_reader.pages:
|
37 |
-
content = page.extract_text()
|
38 |
-
if content:
|
39 |
-
raw_text += content
|
40 |
-
|
41 |
-
# Split text into chunks
|
42 |
-
text_splitter = CharacterTextSplitter(
|
43 |
-
separator="\n", chunk_size=800, chunk_overlap=200, length_function=len
|
44 |
-
)
|
45 |
-
texts = text_splitter.split_text(raw_text)
|
46 |
-
|
47 |
-
# === Embeddings ===
|
48 |
-
embedding = HuggingFaceEmbeddings(
|
49 |
-
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
50 |
-
)
|
51 |
-
|
52 |
-
# === Hugging Face LLM ===
|
53 |
-
llm = HuggingFaceHub(
|
54 |
-
repo_id="mistralai/Mistral-7B-Instruct-v0.1",
|
55 |
-
huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,
|
56 |
-
model_kwargs={"temperature": 0.5, "max_new_tokens": 512}
|
57 |
-
)
|
58 |
-
|
59 |
-
# === Create vector store and index ===
|
60 |
-
vector_store = Cassandra(
|
61 |
-
embedding=embedding,
|
62 |
-
table_name=
|
63 |
-
session=None,
|
64 |
-
keyspace=None,
|
65 |
-
)
|
66 |
-
vector_store.add_texts(texts[:50])
|
67 |
-
st.success(f"π {len(texts[:50])} chunks embedded and stored in AstraDB.")
|
68 |
-
|
69 |
-
astra_vector_index = VectorStoreIndexWrapper(vectorstore=vector_store)
|
70 |
-
|
71 |
-
# === Ask Questions ===
|
72 |
-
st.header("π€ Ask a question about your PDF")
|
73 |
-
user_question = st.text_input("π¬ Type your question here")
|
74 |
-
|
75 |
-
if user_question:
|
76 |
-
with st.spinner("Thinking..."):
|
77 |
-
answer = astra_vector_index.query(user_question, llm=llm).strip()
|
78 |
-
st.markdown(f"### π§ Answer:\n{answer}")
|
79 |
-
|
80 |
-
st.markdown("### π Top Relevant Chunks")
|
81 |
-
docs = vector_store.similarity_search_with_score(user_question, k=4)
|
82 |
-
for i, (doc, score) in enumerate(docs, 1):
|
83 |
-
st.markdown(f"**Chunk {i}** β Relevance Score: `{score:.4f}`")
|
84 |
-
st.code(doc.page_content[:500], language="markdown")
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from PyPDF2 import PdfReader
|
3 |
+
from langchain.vectorstores.cassandra import Cassandra
|
4 |
+
from langchain.indexes.vectorstore import VectorStoreIndexWrapper
|
5 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
6 |
+
from langchain.llms import HuggingFaceHub
|
7 |
+
from langchain.text_splitter import CharacterTextSplitter
|
8 |
+
import cassio
|
9 |
+
from dotenv import load_dotenv
|
10 |
+
import os
|
11 |
+
|
12 |
+
load_dotenv()
|
13 |
+
|
14 |
+
ASTRA_DB_APPLICATION_TOKEN = os.getenv("ASTRA_DB_APPLICATION_TOKEN")
|
15 |
+
ASTRA_DB_ID = os.getenv("ASTRA_DB_ID")
|
16 |
+
HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
17 |
+
|
18 |
+
# === Streamlit UI Setup ===
|
19 |
+
st.set_page_config(page_title="Query PDF with Free Hugging Face Models", layout="wide")
|
20 |
+
st.title("ππ¬ Query PDF using LangChain + AstraDB (Free Hugging Face Models)")
|
21 |
+
|
22 |
+
# === File Upload ===
|
23 |
+
uploaded_file = st.file_uploader("Upload your PDF", type=["pdf"])
|
24 |
+
|
25 |
+
if uploaded_file:
|
26 |
+
st.success("β
PDF uploaded successfully!")
|
27 |
+
process_button = st.button("π Process PDF")
|
28 |
+
|
29 |
+
if process_button:
|
30 |
+
# Initialize AstraDB
|
31 |
+
cassio.init(token=ASTRA_DB_APPLICATION_TOKEN, database_id=ASTRA_DB_ID)
|
32 |
+
|
33 |
+
# Read PDF contents
|
34 |
+
pdf_reader = PdfReader(uploaded_file)
|
35 |
+
raw_text = ""
|
36 |
+
for page in pdf_reader.pages:
|
37 |
+
content = page.extract_text()
|
38 |
+
if content:
|
39 |
+
raw_text += content
|
40 |
+
|
41 |
+
# Split text into chunks
|
42 |
+
text_splitter = CharacterTextSplitter(
|
43 |
+
separator="\n", chunk_size=800, chunk_overlap=200, length_function=len
|
44 |
+
)
|
45 |
+
texts = text_splitter.split_text(raw_text)
|
46 |
+
|
47 |
+
# === Embeddings ===
|
48 |
+
embedding = HuggingFaceEmbeddings(
|
49 |
+
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
50 |
+
)
|
51 |
+
|
52 |
+
# === Hugging Face LLM ===
|
53 |
+
llm = HuggingFaceHub(
|
54 |
+
repo_id="mistralai/Mistral-7B-Instruct-v0.1",
|
55 |
+
huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,
|
56 |
+
model_kwargs={"temperature": 0.5, "max_new_tokens": 512}
|
57 |
+
)
|
58 |
+
|
59 |
+
# === Create vector store and index ===
|
60 |
+
vector_store = Cassandra(
|
61 |
+
embedding=embedding,
|
62 |
+
table_name="qa_mini_demo",
|
63 |
+
session=None,
|
64 |
+
keyspace=None,
|
65 |
+
)
|
66 |
+
vector_store.add_texts(texts[:50])
|
67 |
+
st.success(f"π {len(texts[:50])} chunks embedded and stored in AstraDB.")
|
68 |
+
|
69 |
+
astra_vector_index = VectorStoreIndexWrapper(vectorstore=vector_store)
|
70 |
+
|
71 |
+
# === Ask Questions ===
|
72 |
+
st.header("π€ Ask a question about your PDF")
|
73 |
+
user_question = st.text_input("π¬ Type your question here")
|
74 |
+
|
75 |
+
if user_question:
|
76 |
+
with st.spinner("Thinking..."):
|
77 |
+
answer = astra_vector_index.query(user_question, llm=llm).strip()
|
78 |
+
st.markdown(f"### π§ Answer:\n{answer}")
|
79 |
+
|
80 |
+
st.markdown("### π Top Relevant Chunks")
|
81 |
+
docs = vector_store.similarity_search_with_score(user_question, k=4)
|
82 |
+
for i, (doc, score) in enumerate(docs, 1):
|
83 |
+
st.markdown(f"**Chunk {i}** β Relevance Score: `{score:.4f}`")
|
84 |
+
st.code(doc.page_content[:500], language="markdown")
|