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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
| 1 |
+
# Imports
|
|
|
|
|
|
|
| 2 |
import streamlit as st
|
| 3 |
+
import tempfile
|
| 4 |
+
import os
|
| 5 |
|
| 6 |
+
# LangChain imports
|
| 7 |
+
from langchain_community.document_loaders import (
|
| 8 |
+
PyPDFLoader,
|
| 9 |
+
TextLoader,
|
| 10 |
+
UnstructuredWordDocumentLoader,
|
| 11 |
+
CSVLoader
|
| 12 |
+
)
|
| 13 |
+
from langchain_community.vectorstores import FAISS
|
| 14 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 15 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
| 16 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 17 |
+
from langchain_core.runnables import RunnablePassthrough
|
| 18 |
+
from langchain.embeddings.base import Embeddings
|
| 19 |
+
|
| 20 |
+
# HuggingFace Inference client
|
| 21 |
+
from huggingface_hub import InferenceClient
|
| 22 |
+
|
| 23 |
+
# Load HF API key from Secrets
|
| 24 |
+
HF_TOKEN = os.environ.get("HUGGINGFACE_API_KEY")
|
| 25 |
+
if not HF_TOKEN:
|
| 26 |
+
st.error("HuggingFace API key not found. Add it as a Space Secret: 'HUGGINGFACE_API_KEY'")
|
| 27 |
+
st.stop()
|
| 28 |
+
|
| 29 |
+
# Initialize HF Inference client
|
| 30 |
+
hf_client = InferenceClient(provider="huggingface-inference", api_key=HF_TOKEN)
|
| 31 |
+
|
| 32 |
+
# Embeddings wrapper using HF Inference API
|
| 33 |
+
class HFInferenceEmbeddings(Embeddings):
|
| 34 |
+
def embed_documents(self, texts):
|
| 35 |
+
embeddings = []
|
| 36 |
+
for text in texts:
|
| 37 |
+
res = hf_client.feature_extraction(
|
| 38 |
+
model="intfloat/multilingual-e5-large-instruct",
|
| 39 |
+
inputs=text
|
| 40 |
+
)
|
| 41 |
+
embeddings.append(res[0]) # HF returns a list of vectors
|
| 42 |
+
return embeddings
|
| 43 |
+
|
| 44 |
+
def embed_query(self, text):
|
| 45 |
+
res = hf_client.feature_extraction(
|
| 46 |
+
model="intfloat/multilingual-e5-large-instruct",
|
| 47 |
+
inputs=text
|
| 48 |
+
)
|
| 49 |
+
return res[0]
|
| 50 |
+
|
| 51 |
+
# Setup LLM via HF Endpoint
|
| 52 |
+
llm = HuggingFaceEndpoint(
|
| 53 |
+
repo_id="AI-Sweden-Models/Llama-3-8B-instruct",
|
| 54 |
+
task="text-generation",
|
| 55 |
+
provider="huggingface-inference",
|
| 56 |
+
temperature=0.2,
|
| 57 |
+
max_new_tokens=512,
|
| 58 |
+
api_key=HF_TOKEN,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Streamlit UI
|
| 62 |
+
st.title("Ask RAG - Multi-file Support")
|
| 63 |
+
|
| 64 |
+
uploaded_files = st.file_uploader(
|
| 65 |
+
"Upload files (PDF, DOCX, TXT, CSV)",
|
| 66 |
+
type=["pdf", "docx", "txt", "csv"],
|
| 67 |
+
accept_multiple_files=True
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
@st.cache_resource
|
| 71 |
+
def load_files(files):
|
| 72 |
+
if not files:
|
| 73 |
+
return None, []
|
| 74 |
+
|
| 75 |
+
loaders = []
|
| 76 |
+
temp_files = []
|
| 77 |
+
|
| 78 |
+
for file in files:
|
| 79 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.name)[-1]) as temp_file:
|
| 80 |
+
temp_file.write(file.read())
|
| 81 |
+
temp_path = temp_file.name
|
| 82 |
+
temp_files.append(temp_path)
|
| 83 |
|
| 84 |
+
if file.name.endswith(".pdf"):
|
| 85 |
+
loaders.append(PyPDFLoader(temp_path))
|
| 86 |
+
elif file.name.endswith(".txt"):
|
| 87 |
+
loaders.append(TextLoader(temp_path))
|
| 88 |
+
elif file.name.endswith(".docx"):
|
| 89 |
+
loaders.append(UnstructuredWordDocumentLoader(temp_path))
|
| 90 |
+
elif file.name.endswith(".csv"):
|
| 91 |
+
loaders.append(CSVLoader(temp_path))
|
| 92 |
|
| 93 |
+
documents = []
|
| 94 |
+
for loader in loaders:
|
| 95 |
+
documents.extend(loader.load())
|
| 96 |
+
|
| 97 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
| 98 |
+
docs = text_splitter.split_documents(documents)
|
| 99 |
+
|
| 100 |
+
vectorstore = FAISS.from_documents(docs, HFInferenceEmbeddings())
|
| 101 |
+
return vectorstore, temp_files
|
| 102 |
+
|
| 103 |
+
if uploaded_files:
|
| 104 |
+
vectorstore, temp_files = load_files(uploaded_files)
|
| 105 |
+
else:
|
| 106 |
+
vectorstore, temp_files = None, []
|
| 107 |
+
|
| 108 |
+
if vectorstore:
|
| 109 |
+
retriever = vectorstore.as_retriever()
|
| 110 |
+
|
| 111 |
+
chat_prompt = ChatPromptTemplate.from_template(
|
| 112 |
+
"""Use the context below to answer the question.
|
| 113 |
+
Context:
|
| 114 |
+
{context}
|
| 115 |
+
Question:
|
| 116 |
+
{question}
|
| 117 |
"""
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
def format_docs(docs):
|
| 121 |
+
return "\n\n".join(d.page_content for d in docs)
|
| 122 |
+
|
| 123 |
+
rag_chain = (
|
| 124 |
+
{
|
| 125 |
+
"context": retriever | format_docs,
|
| 126 |
+
"question": RunnablePassthrough(),
|
| 127 |
+
}
|
| 128 |
+
| chat_prompt
|
| 129 |
+
| llm
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
if 'messages' not in st.session_state:
|
| 133 |
+
st.session_state.messages = []
|
| 134 |
+
|
| 135 |
+
for message in st.session_state.messages:
|
| 136 |
+
st.chat_message(message["role"]).markdown(message["content"])
|
| 137 |
+
|
| 138 |
+
user_input = st.chat_input("Enter your prompt")
|
| 139 |
+
if user_input:
|
| 140 |
+
st.chat_message("user").markdown(user_input)
|
| 141 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
| 142 |
+
|
| 143 |
+
response = rag_chain.invoke(user_input)
|
| 144 |
+
answer = response.content
|
| 145 |
+
st.chat_message("assistant").markdown(answer)
|
| 146 |
+
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 147 |
+
|
| 148 |
+
else:
|
| 149 |
+
st.warning("Please upload files to start querying.")
|
| 150 |
|
| 151 |
+
if st.button("Clear All"):
|
| 152 |
+
st.session_state.messages = []
|
| 153 |
+
for file_path in temp_files:
|
| 154 |
+
try:
|
| 155 |
+
os.remove(file_path)
|
| 156 |
+
except Exception as e:
|
| 157 |
+
print(f"Error deleting file {file_path}: {e}")
|
| 158 |
+
st.experimental_rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|