File size: 12,723 Bytes
a267b49
44b8cfd
a267b49
6143b5b
a267b49
 
 
6143b5b
e7d4e44
187fc82
a267b49
 
6143b5b
 
a267b49
41791ed
 
 
2f5d09f
 
a267b49
a91bbdd
a267b49
 
 
 
 
 
 
 
a648bb8
a267b49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b484d7
0044e73
41791ed
 
a267b49
 
 
4b484d7
a267b49
 
 
 
 
 
0044e73
 
a267b49
41791ed
e7d4e44
a267b49
 
 
 
 
 
 
 
 
 
 
 
 
41791ed
 
a267b49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f5d09f
a267b49
 
 
 
 
 
 
 
 
 
 
 
 
 
41791ed
 
a267b49
e7d4e44
a267b49
 
 
41791ed
a267b49
 
 
 
 
e7d4e44
a267b49
aee31d5
a267b49
 
2368f18
a267b49
2368f18
a267b49
a648bb8
2f5d09f
 
a267b49
a648bb8
2f5d09f
a648bb8
2f5d09f
a648bb8
2f5d09f
a648bb8
2368f18
a648bb8
 
 
2368f18
 
a648bb8
2368f18
a648bb8
 
 
a267b49
2e9ebb3
a91bbdd
41791ed
 
 
 
 
 
 
 
 
 
 
6143b5b
a648bb8
 
 
 
 
 
6143b5b
215effb
41791ed
 
 
 
 
 
 
 
 
 
 
 
 
 
a91bbdd
8ebc68d
4b02c5c
 
635fbe7
 
 
 
 
 
 
 
 
 
4b02c5c
 
635fbe7
 
 
 
 
 
4b02c5c
 
635fbe7
 
 
 
 
 
 
 
 
4b02c5c
635fbe7
6143b5b
 
 
5b2e3d1
6143b5b
 
 
 
 
 
 
 
 
41791ed
6143b5b
 
 
 
 
 
41791ed
6143b5b
 
41791ed
 
 
6143b5b
41791ed
6143b5b
 
 
 
 
 
 
 
 
 
 
 
41791ed
6143b5b
 
 
 
41791ed
 
 
 
6143b5b
 
 
 
 
 
 
41791ed
6143b5b
a5251d9
0044e73
 
 
 
4b02c5c
2f5d09f
fc24904
41791ed
fc24904
 
 
 
 
 
 
41791ed
 
fc24904
41791ed
fc24904
 
 
 
6143b5b
 
 
2f5d09f
785300a
 
 
 
 
 
 
 
 
 
 
 
2f5d09f
785300a
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import os
import re
import time
import msgpack
import numpy as np
import streamlit as st
from numpy import ndarray
from scipy.sparse import csr_matrix, save_npz, load_npz, vstack
from qdrant_client import QdrantClient, models
from langchain_community.llms.llamacpp import LlamaCpp
from langchain_community.document_loaders.wikipedia import WikipediaLoader
from langchain_community.document_loaders.unstructured import UnstructuredFileLoader
from langchain_core.prompts import PromptTemplate
from langchain.chains.summarize import load_summarize_chain
from langchain_experimental.text_splitter import SemanticChunker
from fastembed.sparse.splade_pp import supported_splade_models
from fastembed import SparseTextEmbedding, SparseEmbedding
from fastembed_ext import FastEmbedEmbeddingsLc
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_core.documents import Document
from huggingface_hub import hf_hub_download
from qdrant_client.models import (
    NamedSparseVector,
    NamedVector,
    SparseVector,
    PointStruct,
    SearchRequest,
    ScoredPoint,
)
from llama_cpp import Llama

MAP_PROMPT = """
You will be given a single passage of a book. This section will be enclosed in triple backticks (```)
Your goal is to give a summary of this section so that a reader will have a full understanding of what happened.
Your response should be at least three paragraphs and fully encompass what said in the passage.

```{text}```
FULL SUMMARY:
"""

COMBINE_PROMPT = """
You will be given a series of summaries from a book. The summaries will be enclosed in triple backticks (```)
Your goal is to give a verbose summary of what happened in the story.
The reader should be able to grasp what happened in the book.

```{text}```
VERBOSE SUMMARY:
"""


def make_points(chunks: list[str], dense: list[ndarray], sparse: list[SparseEmbedding])-> list[PointStruct]:
    points = []
    for idx, (sparse_vector, chunk, dense_vector) in enumerate(zip(sparse, chunks, dense)):
        sparse_vec = SparseVector(indices=sparse_vector.indices.tolist(), values=sparse_vector.values.tolist())
        point = PointStruct(
            id=idx,
            vector={
                "text-sparse": sparse_vec,
                "text-dense": dense_vector,
            },
            payload={
                "text": chunk
            }
        )
        points.append(point)
    return points

def search(client: QdrantClient, collection_name: str, dense, sparse):
    search_results = client.search_batch(
        collection_name,
        [
            SearchRequest(
                vector=NamedVector(
                    name="text-dense",
                    vector=dense,
                ),
                limit=10
            ),
            SearchRequest(
                vector=NamedSparseVector(
                    name="text-sparse",
                    vector=SparseVector(
                        indices=sparse[0].indices.tolist(),
                        values=sparse[0].values.tolist(),
                    ),
                ),
                limit=10
            ),
        ],
    )

    return search_results

def rank_list(search_result: list[ScoredPoint]):
    return [(point.id, rank + 1) for rank, point in enumerate(search_result)]

def rrf(rank_lists, alpha=60, default_rank=1000):
    """
    Optimized Reciprocal Rank Fusion (RRF) using NumPy for large rank lists.

    :param rank_lists: A list of rank lists. Each rank list should be a list of (item, rank) tuples.
    :param alpha: The parameter alpha used in the RRF formula. Default is 60.
    :param default_rank: The default rank assigned to items not present in a rank list. Default is 1000.
    :return: Sorted list of items based on their RRF scores.
    """
    all_items = set(item for rank_list in rank_lists for item, _ in rank_list)
    item_to_index = {item: idx for idx, item in enumerate(all_items)}
    rank_matrix = np.full((len(all_items), len(rank_lists)), default_rank)

    for list_idx, rank_list in enumerate(rank_lists):
        for item, rank in rank_list:
            rank_matrix[item_to_index[item], list_idx] = rank

    rrf_scores = np.sum(1.0 / (alpha + rank_matrix), axis=1)
    sorted_indices = np.argsort(-rrf_scores)
    sorted_items = [(list(item_to_index.keys())[idx], rrf_scores[idx]) for idx in sorted_indices]

    return sorted_items


def main(query: str, client: QdrantClient, collection_name: str, llm, dense_model, sparse_model):
     # name = 'Kia_EV6'
    # filepath = os.path.join(os.getcwd(), name + '.pdf')

    # docs = UnstructuredFileLoader(
    #     file_path=filepath,
    #     mode='elements',
    #     strategy='hi_res',
    #     skip_infer_table_types=['png', 'pdf', 'jpg', 'xls', 'xlsx', 'heic'],
    #     hi_res_model_name='yolox',
    #     include_page_breaks=True
    # )

    # docs = docs.load()
    
    dense_query = list(dense_model.embed_query(query, 32))
    sparse_query = list(sparse_model.embed(query, 32))

    search_results = search(
        client,
        collection_name,
        dense_query,
        sparse_query
    )

    dense_rank_list, sparse_rank_list = rank_list(search_results[0]), rank_list(search_results[1])
    rrf_rank_list = rrf([dense_rank_list, sparse_rank_list])

    records_list = client.retrieve(
        collection_name,
        [item[0] for item in rrf_rank_list]
    )
    
    docs = [record.payload['text'] for record in records_list[:3]]

    combined_docs = "\n".join(docs)

    template = f"""Q: Use the following pieces of context to answer the question at the end.
    If you don't know the answer, just say that you don't know, don't try to make up an answer.
    Use three sentences maximum and keep the answer as concise as possible.
    
    {combined_docs}
    
    Question: {query}
    
    A: """

    response = llm(template, stop=["Q:", "\n"], temperature=0.7)

    text = response["choices"][0]["text"]

    prompt = f"""Q: Write a summary of the following text delimited by triple backquotes that includes the main points and any important details.
    Return your response in bullet points which covers the key points of the text.
    ```{text}```
    A :
    """

    output = llm(prompt, stop=["Q:", "\n"], temperature=0.7, max_tokens)
    return output["choices"][0]["text"]

@st.cache_resource
def load_models_and_documents():
    supported_splade_models[0] = {
        "model": "prithivida/Splade_PP_en_v2",
        "vocab_size": 30522,
        "description": "Implementation of SPLADE++ Model for English v2",
        "size_in_GB": 0.532,
        "sources": {
            "hf": "devve1/Splade_PP_en_v2_onnx"
        },
        "model_file": "model.onnx"
    }
    
    with st.spinner('Load models...'):
        llm = Llama.from_pretrained(
            repo_id="MaziyarPanahi/Llama-3-8B-Instruct-32k-v0.1-GGUF",
            filename="*Q8_0.gguf",
            verbose=False,
            n_ctx=16000,
            n_gpu_layers=32
        )

        provider = ['CPUExecutionProvider']
        
        dense_model = FastEmbedEmbeddingsLc(
            model_name='mixedbread-ai/mxbai-embed-large-v1',
            providers=provider,
            cache_dir=os.getenv('HF_HOME'),
            batch_size=32
        )
        
        sparse_model = SparseTextEmbedding(
            'prithivida/Splade_PP_en_v2',
            cache_dir=os.getenv('HF_HOME'),
            providers=provider
        )

    client = QdrantClient(':memory:')
    collection_name = 'collection_demo'
    
    client.create_collection(
        collection_name,
        {
            "text-dense": models.VectorParams(
                size=1024,
                distance=models.Distance.COSINE,
                on_disk=False,
                quantization_config=models.BinaryQuantization(
                    binary=models.BinaryQuantizationConfig(
                        always_ram=True
                    )
                )
            )
        },
        {
            "text-sparse": models.SparseVectorParams(
                index=models.SparseIndexParams(
                    on_disk=False
                )
            )
        },
        2,
        optimizers_config=models.OptimizersConfigDiff(
            indexing_threshold=0
        ),
        hnsw_config=models.HnswConfigDiff(
            on_disk=False, 
            m=16, 
            ef_construct=100
        )
    )
        
    with st.spinner('Parse and chunk documents...'):
        name = 'action_rpg'
        embeddings_path = os.path.join(os.getenv('HF_HOME'), 'embeddings')

        chunks_path = os.path.join(embeddings_path, name + '_chunks.msgpack')
        dense_path = os.path.join(embeddings_path, name + '_dense.npz')
        sparse_path = os.path.join(embeddings_path, name + '_sparse.npz')

        if not os.path.exists(embeddings_path):
            os.mkdir(embeddings_path)

            docs = WikipediaLoader(query='Action-RPG').load()
            chunks, dense_embeddings, sparse_embeddings = chunk_documents(docs, dense_model, sparse_model)

            with open(chunks_path, "wb") as outfile:
                packed = msgpack.packb(chunks, use_bin_type=True)
                outfile.write(packed)
            
            np.savez_compressed(dense_path, *dense_embeddings)
            max_index = max(np.max(embedding.indices) for embedding in sparse_embeddings)
        
            sparse_matrices = []
            for embedding in sparse_embeddings:
                data = embedding.values
                indices = embedding.indices
                indptr = np.array([0, len(data)])
                matrix = csr_matrix((data, indices, indptr), shape=(1, max_index + 1))
                sparse_matrices.append(matrix)
            
            combined_sparse_matrix = vstack(sparse_matrices)
            save_npz(sparse_path, combined_sparse_matrix)
        else:
            with open(chunks_path, "rb") as data_file:
                byte_data = data_file.read()
                
            chunks = msgpack.unpackb(byte_data, raw=False)

            dense_embeddings = list(np.load(dense_path).values())

            sparse_embeddings = []
            loaded_sparse_matrix = load_npz(sparse_path)
        
            for i in range(loaded_sparse_matrix.shape[0]):
                row = loaded_sparse_matrix.getrow(i)
                values = row.data
                indices = row.indices
                embedding = SparseEmbedding(values, indices)
                sparse_embeddings.append(embedding)

    with st.spinner('Save documents...'):
        client.upsert(
            collection_name,
            make_points(
                chunks, 
                dense_embeddings, 
                sparse_embeddings
            )
        )
    client.update_collection(
        collection_name=collection_name,
        optimizer_config=models.OptimizersConfigDiff(indexing_threshold=20000)
    )

    return client, collection_name, llm, dense_model, sparse_model

def chunk_documents(docs, dense_model, sparse_model):
    text_splitter = SemanticChunker(
        dense_model,
        breakpoint_threshold_type='standard_deviation'
    )

    documents = [doc.page_content for doc in text_splitter.transform_documents(list(docs))]

    dense_embeddings = dense_model.embed_documents(documents,32)
    sparse_embeddings = list(sparse_model.embed(documents, 32))
    
    return documents, dense_embeddings, sparse_embeddings
    
if __name__ == '__main__':
    st.set_page_config(page_title="Video Game Assistant",
                       layout="wide"
                       )
    st.title("Video Game Assistant :sunglasses:")
    
    client, collection_name, llm, dense_model, sparse_model = load_models_and_documents()

    if "messages" not in st.session_state:
        st.session_state.messages = []

    for message in st.session_state.messages:
        with st.chat_message(message["role"]):
            st.markdown(message["content"])

    if prompt := st.chat_input("Message Video Game Assistant"):
        st.chat_message("user").markdown(prompt)
        st.session_state.messages.append({"role": "user", "content": prompt})

        ai_response = main(prompt, client, collection_name, llm, dense_model, sparse_model)
        response = f"Echo: {ai_response}"
        with st.chat_message("assistant"):
            message_placeholder = st.empty()
            full_response = ""
            for chunk in re.split(r'(\s+)', response):
                full_response += chunk + " "
                time.sleep(0.01)
                message_placeholder.markdown(full_response + "▌")
        st.session_state.messages.append({"role": "assistant", "content": full_response})