jsminenguyen commited on
Commit
ab2516e
·
verified ·
1 Parent(s): 9474569

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -0
app.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import InferenceClient
2
+ # Step 1 from the Semantic Search
3
+ from sentence_transformers import SentenceTransformer
4
+ import torch
5
+ import gradio as gr
6
+ import random
7
+
8
+ # Making requests to the model to generate responses:
9
+ client = InferenceClient('Qwen/Qwen2.5-72B-Instruct')
10
+
11
+ # ============================================
12
+
13
+ # Step 2 from the semantic search
14
+ # Open the water_cycle.txt file in read mode with UTF-8 encoding
15
+ with open("Joy_Scout_info.txt", "r", encoding="utf-8") as file:
16
+ # Read the entire contents of the file and store it in a variable
17
+ joyscout_info_text = file.read()
18
+
19
+ # Print the text below
20
+ print(joyscout_info_text)
21
+
22
+
23
+ # =============================================
24
+ # Step 3:
25
+ def preprocess_text(text):
26
+ # Strip extra whitespace from the beginning and the end of the text
27
+ cleaned_text = text.strip()
28
+
29
+ # Split the cleaned_text by every newline character (\n)
30
+ chunks = cleaned_text.split("\n")
31
+
32
+ # Create an empty list to store cleaned chunks
33
+ cleaned_chunks = []
34
+
35
+ # Write your for-in loop below to clean each chunk and add it to the cleaned_chunks list
36
+ for chunk in chunks:
37
+ cleaned_chunks.append(chunk)
38
+
39
+ # Print cleaned_chunks
40
+ print(cleaned_chunks)
41
+
42
+ # Print the length of cleaned_chunks
43
+ print(len(cleaned_chunks))
44
+
45
+ # Return the cleaned_chunks
46
+ return cleaned_chunks
47
+
48
+ # Call the preprocess_text function and store the result in a cleaned_chunks variable
49
+ cleaned_chunks = preprocess_text(joyscout_info_text) # Complete this line
50
+
51
+ # Load the pre-trained embedding model that converts text to vectors
52
+ model = SentenceTransformer('all-MiniLM-L6-v2')
53
+
54
+ # ============================================
55
+
56
+ # Step 4:
57
+ def create_embeddings(text_chunks):
58
+ # Convert each text chunk into a vector embedding and store as a tensor
59
+ chunk_embeddings = model.encode(text_chunks, convert_to_tensor=True) # Replace ... with the text_chunks list
60
+
61
+ # Print the chunk embeddings
62
+ print(chunk_embeddings)
63
+
64
+ # Print the shape of chunk_embeddings
65
+ print(len(chunk_embeddings))
66
+
67
+ # Return the chunk_embeddings
68
+ return chunk_embeddings
69
+
70
+ # Call the create_embeddings function and store the result in a new chunk_embeddings variable
71
+ chunk_embeddings = create_embeddings(cleaned_chunks) # Complete this line
72
+
73
+
74
+ # =====================================
75
+
76
+ # Step 5:
77
+ # Define a function to find the most relevant text chunks for a given query, chunk_embeddings, and text_chunks
78
+ def get_top_chunks(query, chunk_embeddings, text_chunks):
79
+ # Convert the query text into a vector embedding
80
+ query_embedding = model.encode(query, convert_to_tensor=True) # Complete this line
81
+
82
+ # Normalize the query embedding to unit length for accurate similarity comparison
83
+ query_embedding_normalized = query_embedding / query_embedding.norm()
84
+
85
+ # Normalize all chunk embeddings to unit length for consistent comparison
86
+ chunk_embeddings_normalized = chunk_embeddings / chunk_embeddings.norm(dim=1, keepdim=True)
87
+
88
+ # Calculate cosine similarity between query and all chunks using matrix multiplication
89
+ similarities = torch.matmul(chunk_embeddings_normalized, query_embedding_normalized) # Complete this line
90
+
91
+ # Print the similarities
92
+ print(similarities)
93
+
94
+ # Find the indices of the 3 chunks with highest similarity scores
95
+ top_indices = torch.topk(similarities, k=3).indices
96
+
97
+ # Print the top indices
98
+ print(top_indices)
99
+
100
+ # Create an empty list to store the most relevant chunks
101
+ top_chunks = []
102
+ # Creating an empty list to now store our most SIMILAR indices
103
+
104
+
105
+ # Loop through the top indices and retrieve the corresponding text chunks
106
+ for index in top_indices: # Looping through where our chunks are currently stored and now appending the most similar to be in our new list
107
+ top_chunks.append(text_chunks[index])
108
+ # List of the actual chunks needs to be created based on the index values that the top indices list consists of
109
+
110
+ # Return the list of most relevant chunks
111
+ return top_chunks
112
+ # =====================================
113
+
114
+ # Step 7: Putting data into the dictionary:
115
+
116
+
117
+ # ======================================
118
+ def respond(message, history):
119
+ best_chunks = get_top_chunks(message, chunk_embeddings, cleaned_chunks)
120
+ print(best_chunks)
121
+
122
+ str_chunks = "/n".join(best_chunks)
123
+ messages = [{'role':'system', 'content': 'You are a very kind chatbot giving people hobby suggestions to help them spend less time on their electronic devices. You answer their questions based on ' + str_chunks + '.'}]
124
+
125
+ if history:
126
+ messages.extend(history)
127
+
128
+
129
+ messages.append({'role':'user', 'content': message})
130
+
131
+ response = client.chat_completion(messages, max_tokens=100, temperature=1.7, top_p=.3)
132
+ # Temp and top_p control randomness
133
+
134
+ return response['choices'][0]['message']['content'].strip()
135
+
136
+ chat_theme = gr.themes.Soft(
137
+ primary_hue="orange",
138
+ secondary_hue="purple",
139
+ neutral_hue="yellow",
140
+ spacing_size="lg",
141
+ radius_size="lg",
142
+ text_size="lg",
143
+ font=[gr.themes.GoogleFont("IBM Plex Sans"), "sans-serif"],
144
+ font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "monospace"]
145
+ ).set(
146
+ # Input area
147
+ input_background_fill="*neutral_50",
148
+ input_border_color_focus="*primary_300",
149
+ # Button styling
150
+ button_primary_background_fill="*primary_500",
151
+ button_primary_background_fill_hover="*primary_400"
152
+ )
153
+ chatbot = gr.ChatInterface(respond, type="messages", theme=chat_theme)
154
+ chatbot.launch(ssr_mode=False)
155
+ with gr.Blocks(theme= chat_theme) as chatbot:
156
+ with gr.Row(scale=1):
157
+ gr.Image("icecream.jpg")
158
+ with gr.Row(scale=2)
159
+ value="icecream.jpg",
160
+ show_label=False,
161
+ show_share_button = False,
162
+ show_download_button = False)
163
+ gr.ChatInterface(respond, type="messages")
164
+
165
+ chatbot = gr.ChatInterface(respond, type="messages")
166
+ chatbot.launch()