Spaces:
Sleeping

Paul Bilan commited on
Commit
fdb663d
·
1 Parent(s): 3f47ad0

updated requirements.txt and RAG code

Browse files
Files changed (3) hide show
  1. requirements-dev.txt +1 -0
  2. requirements.txt +10 -3
  3. src/streamlit_app.py +186 -34
requirements-dev.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ruff==0.7.4
requirements.txt CHANGED
@@ -1,3 +1,10 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
 
 
1
+ chromadb==0.5.20
2
+ sentence-transformers==3.3.1
3
+ streamlit==1.40.1
4
+ PyMuPDF==1.24.14
5
+ langchain-community==0.3.7
6
+ transformers==4.41.0
7
+ torch==2.2.0
8
+ accelerate==0.27.2
9
+
10
+
src/streamlit_app.py CHANGED
@@ -1,40 +1,192 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
 
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
 
 
 
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
 
 
 
 
 
 
 
14
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
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
+ import os
2
+ import tempfile
3
+
4
+ import chromadb
5
  import streamlit as st
6
+ from sentence_transformers import SentenceTransformer
7
+ from langchain_community.document_loaders import PyMuPDFLoader
8
+ from langchain_core.documents import Document
9
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
10
+ from sentence_transformers import CrossEncoder
11
+ from streamlit.runtime.uploaded_file_manager import UploadedFile
12
+ from transformers import pipeline
13
+ #=======================================================================================================================
14
+ # Initialize the embedding model
15
+ @st.cache_resource
16
+ def get_embedding_model():
17
+ return SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
18
+ #=======================================================================================================================
19
+ class EmbeddingFunction:
20
+ def __init__(self):
21
+ self.model = get_embedding_model()
22
+
23
+ def __call__(self, input: list[str]) -> list[list[float]]:
24
+ return self.model.encode(input).tolist()
25
+ #=======================================================================================================================
26
+ def get_embeddings(texts):
27
+ """Generate embeddings using sentence-transformers."""
28
+ model = get_embedding_model()
29
+ return model.encode(texts).tolist()
30
+ #=======================================================================================================================
31
+ system_prompt = """
32
+ You are an AI assistant tasked with providing detailed answers based solely on the given context. Your goal is to analyze the information provided and formulate a comprehensive, well-structured response to the question.
33
 
34
+ context will be passed as "Context:"
35
+ user question will be passed as "Question:"
36
 
37
+ To answer the question:
38
+ 1. Thoroughly analyze the context, identifying key information relevant to the question.
39
+ 2. Organize your thoughts and plan your response to ensure a logical flow of information.
40
+ 3. Formulate a detailed answer that directly addresses the question, using only the information provided in the context.
41
+ 4. Ensure your answer is comprehensive, covering all relevant aspects found in the context.
42
+ 5. If the context doesn't contain sufficient information to fully answer the question, state this clearly in your response.
43
 
44
+ Format your response as follows:
45
+ 1. Use clear, concise language.
46
+ 2. Organize your answer into paragraphs for readability.
47
+ 3. Use bullet points or numbered lists where appropriate to break down complex information.
48
+ 4. If relevant, include any headings or subheadings to structure your response.
49
+ 5. Ensure proper grammar, punctuation, and spelling throughout your answer.
50
+
51
+ Important: Base your entire response solely on the information provided in the context. Do not include any external knowledge or assumptions not present in the given text.
52
  """
53
+ #=======================================================================================================================
54
+ def process_document(uploaded_file: UploadedFile) -> list[Document]:
55
+ """Processes an uploaded PDF file by converting it to text chunks."""
56
+ temp_file = tempfile.NamedTemporaryFile("wb", suffix=".pdf", delete=False)
57
+ temp_file.write(uploaded_file.read())
58
+
59
+ loader = PyMuPDFLoader(temp_file.name)
60
+ docs = loader.load()
61
+ temp_file.close()
62
+
63
+ os.unlink(temp_file.name)
64
+ text_splitter = RecursiveCharacterTextSplitter(
65
+ chunk_size=400,
66
+ chunk_overlap=100,
67
+ separators=["\n\n", "\n", ".", "?", "!", " ", ""],
68
+ )
69
+ return text_splitter.split_documents(docs)
70
+ #=======================================================================================================================
71
+ def get_vector_collection() -> chromadb.Collection:
72
+ """Gets or creates a ChromaDB collection for vector storage."""
73
+ chroma_client = chromadb.PersistentClient(path="./demo-rag-chroma")
74
+ return chroma_client.get_or_create_collection(
75
+ name="rag_app",
76
+ embedding_function=EmbeddingFunction(),
77
+ metadata={"hnsw:space": "cosine"},
78
+ )
79
+ #=======================================================================================================================
80
+ def add_to_vector_collection(all_splits: list[Document], file_name: str):
81
+ """Adds document splits to a vector collection for semantic search."""
82
+ collection = get_vector_collection()
83
+ documents, metadatas, ids = [], [], []
84
+
85
+ for idx, split in enumerate(all_splits):
86
+ documents.append(split.page_content)
87
+ metadatas.append(split.metadata)
88
+ ids.append(f"{file_name}_{idx}")
89
+
90
+ collection.upsert(
91
+ documents=documents,
92
+ metadatas=metadatas,
93
+ ids=ids,
94
+ )
95
+ st.success("Data added to the vector store!")
96
+ #=======================================================================================================================
97
+ def query_collection(prompt: str, n_results: int = 10):
98
+ """Queries the vector collection with a given prompt to retrieve relevant documents."""
99
+ collection = get_vector_collection()
100
+ results = collection.query(query_texts=[prompt], n_results=n_results)
101
+ return results
102
+ #=======================================================================================================================
103
+ def call_llm(context: str, prompt: str):
104
+ """Calls the language model with context and prompt to generate a response."""
105
+ # Get the Hugging Face token from hugging space secret environment variables
106
+ hf_token = os.getenv('rag2') # Changed to match your secret name
107
+
108
+ # Initialize the pipeline for text generation with the token
109
+ generator = pipeline(
110
+ "text-generation",
111
+ model="mistralai/Mistral-7B-Instruct-v0.2",
112
+ token=hf_token
113
+ )
114
+
115
+ # Format the input text
116
+ input_text = f"Context: {context}\nQuestion: {prompt}\nAnswer:"
117
+
118
+ # Generate response
119
+ response = generator(input_text, max_length=512, num_return_sequences=1)
120
+ return response[0]['generated_text']
121
+ #=======================================================================================================================
122
+ def re_rank_cross_encoders(documents: list[str], prompt: str) -> tuple[str, list[int]]:
123
+ """Re-ranks documents using a cross-encoder model for more accurate relevance scoring."""
124
+ relevant_text = ""
125
+ relevant_text_ids = []
126
+
127
+ encoder_model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
128
+
129
+ # Limit documents to reasonable batch size
130
+ batch_size = min(len(documents), 32)
131
+ documents_batch = documents[:batch_size]
132
+
133
+ # Handle potential ranking errors
134
+ try:
135
+ ranks = encoder_model.rank(prompt, documents_batch, top_k=min(3, len(documents)))
136
+ for rank in ranks:
137
+ corpus_id = rank["corpus_id"]
138
+ if corpus_id < len(documents_batch):
139
+ relevant_text += documents_batch[corpus_id]
140
+ relevant_text_ids.append(corpus_id)
141
+ except Exception as e:
142
+ st.error(f"Cross-encoder ranking failed: {str(e)}")
143
+ return documents[0], [0]
144
+
145
+ return relevant_text, relevant_text_ids
146
+ # old code below:
147
+ #ranks = encoder_model.rank(prompt, documents, top_k=3)
148
+ #for rank in ranks:
149
+ # relevant_text += documents[rank["corpus_id"]]
150
+ # relevant_text_ids.append(rank["corpus_id"])
151
+
152
+ #return relevant_text, relevant_text_ids
153
+ #=======================================================================================================================
154
+ if __name__ == "__main__":
155
+ # Document Upload Area
156
+ with st.sidebar:
157
+ st.set_page_config(page_title="RAG Question Answer")
158
+ uploaded_file = st.file_uploader(
159
+ "**📑 Upload PDF files for QnA**", type=["pdf"], accept_multiple_files=False
160
+ )
161
+
162
+ process = st.button(
163
+ "⚡️ Process",
164
+ )
165
+ if uploaded_file and process:
166
+ normalize_uploaded_file_name = uploaded_file.name.translate(
167
+ str.maketrans({"-": "_", ".": "_", " ": "_"})
168
+ )
169
+ all_splits = process_document(uploaded_file)
170
+ add_to_vector_collection(all_splits, normalize_uploaded_file_name)
171
+
172
+ # Question and Answer Area
173
+ st.header("🗣️ RAG Question Answer")
174
+ prompt = st.text_area("**Ask a question related to your document:**")
175
+ ask = st.button(
176
+ "🔥 Ask",
177
+ )
178
+
179
+ if ask and prompt:
180
+ results = query_collection(prompt)
181
+ context = results.get("documents")[0]
182
+ relevant_text, relevant_text_ids = re_rank_cross_encoders(context, prompt)
183
+ response = call_llm(context=relevant_text, prompt=prompt)
184
+ st.write(response)
185
+
186
+ with st.expander("See retrieved documents"):
187
+ st.write(results)
188
 
189
+ with st.expander("See most relevant document ids"):
190
+ st.write(relevant_text_ids)
191
+ st.write(relevant_text)
192
+ #=======================================================================================================================