File size: 7,556 Bytes
1507263
304cc9a
1507263
 
 
 
 
 
 
 
 
 
 
 
 
 
693506b
8ab45c8
304cc9a
5ac7343
1507263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ac7343
1507263
 
 
25be18c
 
1507263
 
25be18c
5ac7343
 
1507263
 
5ac7343
1507263
 
5ac7343
 
1507263
 
 
5ac7343
1507263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ac7343
 
 
 
8ab45c8
 
1507263
 
5ac7343
1507263
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
# App Main file
# from travel import ui as travel_ui

import os
import uuid
from typing import List, Sequence
import warnings

from langchain_community.document_loaders import CSVLoader
from langchain.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter

from qdrant_client import QdrantClient, models
from sentence_transformers import SentenceTransformer
import gradio as gr

from event_ui import ui as events_ui
from fashion import ui as fashion_ui
from travel_v2 import ui as travel_ui

warnings.filterwarnings("ignore")

MODELS_ENABLED = [
    "gemini-2.0-flash",
    "gemini-1.5-flash",
]

# Use a persistent local path for Qdrant data
QDRANT_PATH = './qdrant_data/'+uuid.uuid4().hex
qdrant_client = QdrantClient(path=QDRANT_PATH)
model = SentenceTransformer("all-mpnet-base-v2")

# Collection name for storing document chunks
COLLECTION_NAME = 'tmp_collection'

# Function to create the Qdrant collection if it doesn't exist


def create_collection(collection_name: str, vector_size: int, ):
    """
    Creates a Qdrant collection with the specified name, vector size, and
    distance metric.

    Args:
        collection_name (str): The name of the collection to create.
        vector_size (int): The size of the vectors to be stored in the
                            collection.
        distance (str, optional): The distance metric to use for vector
                                  comparison.
                                   Defaults to "Cosine".
                                   Other options: "Dot", "Euclid"
    """
    distance_m = models.Distance.COSINE

    try:
        qdrant_client.create_collection(
            collection_name=collection_name,
            vectors_config=models.VectorParams(
                size=vector_size, distance=distance_m),
        )
        print(f"Collection '{collection_name}' created successfully.")
    except Exception as e:  # pylint: disable=broad-except
        print(f"Error creating collection '{collection_name}': {e}")

# Function to chunk the text into smaller parts


def chunk_text(
        text: str,
        chunk_size: int = 500,
        chunk_overlap: int = 50
) -> Sequence[Document]:
    """
    Chunks a large text into smaller documents.

    Args:
        text (str): The text to chunk.
        chunk_size (int, optional): The maximum size of each chunk.
                                    Defaults to 500.
        chunk_overlap (int, optional): The amount of overlap between chunks.
                                        Defaults to 50.

    Returns:
        List[Document]: A list of Document objects, each representing a chunk.
    """
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=chunk_size,
        chunk_overlap=chunk_overlap,
        separators=["\n\n", "\n", " ", ""],
    )
    chunks = text_splitter.create_documents([text])
    return chunks


# Function to embed the text chunks using the Sentence Transformer model
def embed_chunks(chunks: List[Document]) -> List[List[float]]:
    """
    Embeds a list of text chunks using the Sentence Transformer model.

    Args:
        chunks (List[Document]): A list of Document objects, each representing
                                 a chunk.

    Returns:
        List[List[float]]: A list of embeddings for each chunk.
    """
    text_chunks = [chunk.page_content for chunk in chunks]
    embeddings = model.encode(text_chunks).tolist()
    return embeddings

# Function to upload chunks to Qdrant


def upload_to_qdrant(
        chunks: List[Document],
        embeddings: List[List[float]],
        collection_name: str
):
    """
    Uploads text chunks and their embeddings to Qdrant.

    Args:
        chunks (List[Document]): A list of Document objects.
        embeddings (List[List[float]]): A list of embeddings for each chunk.
        collection_name (str): The name of the Qdrant collection to upload to.
    """
    points = []
    for i, chunk in enumerate(chunks):
        points.append(
            models.PointStruct(
                id=uuid.uuid4().hex,
                vector=embeddings[i],
                payload={
                    "text": chunk.page_content,
                    "metadata": chunk.metadata,
                },
            )
        )
    qdrant_client.upsert(collection_name=collection_name, points=points)


def parse_document(file_path: str) -> str:
    """
    Parses a document and returns the text content.

    Args:
        file_path (str): The path to the document file.

    Returns:
        str: The text content of the document.
    """
    with open(file_path, "r", encoding='utf-8') as file:
        text = file.read()
    return text


def process_file(file_obj: gr.File) -> str:
    """
    Processes an uploaded file, parses it, chunks it, embeds the chunks, and
    uploads to Qdrant.

    Args:
        file_obj (gr.File): The uploaded file object.

    Returns:
        str: A message indicating the success or failure of the process.
    """

    try:
        file_path = file_obj.name
        # create a collection if not exists
        if not qdrant_client.collection_exists(COLLECTION_NAME):
            create_collection(
                collection_name=COLLECTION_NAME,
                vector_size=768,
            )
        # Parse
        text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=500,
            chunk_overlap=50,
            separators=["\n\n", "\n", " ", ""],
        )
        chunks = CSVLoader(
            file_path=file_path
        ).load_and_split(
            text_splitter
        )
        embeddings = embed_chunks(chunks)
        upload_to_qdrant(chunks, embeddings, COLLECTION_NAME)
        print(len(chunks), "chunks uploaded to Qdrant.")

        return f"File '{os.path.basename(file_path)}' processed!"
    except Exception as e:  # pylint: disable=broad-except
        return f"Error processing file: {e}"


with gr.Blocks(
    title='Planner Demos',
    # theme=gr.themes.Origin(),
) as demo:
    gr.Markdown("""# Sample GenAI Demos

    > Note: get ypur gemini API key from:
    > https://ai.google.dev/gemini-api/docs/api-key
    """)
    with gr.Accordion(label='Model Config') as config:
        api_key = gr.Text(
            placeholder='Gemini API key',
            label='Gemini API Key',
            interactive=True,
            value=os.getenv("GEMINI_API_KEY"),
            visible=False
        )
        gemini_model_name = gr.Dropdown(
            label='Gemini Model',
            value=MODELS_ENABLED[0],
            choices=MODELS_ENABLED,
        )
        with gr.Accordion(
            label='Upload Personal Dataset',
            open=False
        ) as dataset:
            dataset_upload = gr.File(
                label='Upload Personal Dataset',
                interactive=True,
            )
            upload_button = gr.Button("Process and Upload")
            output = gr.Textbox(label="Status")
            upload_button.click(  # pylint: disable=no-member
                process_file,
                inputs=dataset_upload,
                outputs=output
            )

    with gr.Accordion(label='Planners') as planners:
        with gr.Tab(label='Travel Planner'):
            travel_ui(api_key, gemini_model_name)
        with gr.Tab(label='Fashion Advisor'):
            fashion_ui(api_key, gemini_model_name)
        with gr.Tab(label='Beauty Advisor'):
            events_ui(api_key, gemini_model_name)

demo.launch(debug=True, server_port=int(os.getenv("PORT", "7860")))