Janec09 commited on
Commit
7f05e6b
·
verified ·
1 Parent(s): 7ff2c4e

Added Semantic Search Feature to Chatbot

Browse files
Files changed (1) hide show
  1. app.py +105 -1
app.py CHANGED
@@ -2,6 +2,104 @@
2
  import gradio as gr
3
  import random
4
  from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  #AI API being used
7
  client= InferenceClient("Qwen/Qwen2.5-7B-Instruct-1M")
@@ -19,7 +117,13 @@ def respond(message,history):
19
  response=client.chat_completion(messages, max_tokens=100) #capping how many words the LLM is allowed to generate as a respond (100 words)
20
 
21
  return response['choices'][0]['message']['content'].strip() #storing value of response in a readable format to display
22
-
 
 
 
 
 
 
23
 
24
  #Defining chatbot giving user a UI to interact, see their conversation history, and see new messages using built in gr feature
25
  #ChatInterface requires at least one parameter(a function)
 
2
  import gradio as gr
3
  import random
4
  from huggingface_hub import InferenceClient
5
+ #STEP 1: Import Sentence Transformer Library And Torch
6
+ from sentence_transformers import SentenceTransformer
7
+ import torch
8
+
9
+ with open("poverty_and_education.txt", "r", encoding="utf-8") as file:
10
+ # Read the entire contents of the file and store it in a variable
11
+ poverty_and_education = file.read()
12
+
13
+ # Print the text below
14
+ print(poverty_and_education)
15
+
16
+ # ===== APPLY THE COMPLETE WORKFLOW =====
17
+
18
+ ### STEP 3
19
+ def preprocess_text(text):
20
+ # Strip extra whitespace from the beginning and the end of the text
21
+ cleaned_text = text.strip()
22
+
23
+ # Split the cleaned_text by every newline character (\n)
24
+ chunks = cleaned_text.split("\n")
25
+
26
+ # Create an empty list to store cleaned chunks
27
+ cleaned_chunks = []
28
+
29
+ # Write your for-in loop below to clean each chunk and add it to the cleaned_chunks list
30
+ for chunk in chunks:
31
+ stripped_chunk = chunk.strip()
32
+ if len(stripped_chunk) > 0:
33
+ cleaned_chunks.append(stripped_chunk)
34
+
35
+ # Print cleaned_chunks
36
+ print(cleaned_chunks)
37
+
38
+ # Print the length of cleaned_chunks
39
+ num_of_chunks = print(len(cleaned_chunks))
40
+
41
+ print(f"There are {num_of_chunks} amount of chunks")
42
+ # Return the cleaned_chunks
43
+ return cleaned_chunks
44
+
45
+ # Load the pre-trained embedding model that converts text to vectors
46
+ model = SentenceTransformer('all-MiniLM-L6-v2')
47
+
48
+ ### STEP 4
49
+ def create_embeddings(text_chunks):
50
+ # Convert each text chunk into a vector embedding and store as a tensor
51
+ chunk_embeddings = model.encode(text_chunks, convert_to_tensor=True) # Replace ... with the text_chunks list
52
+
53
+ # Print the chunk embeddings
54
+ print(chunk_embeddings)
55
+
56
+ # Print the shape of chunk_embeddings
57
+ print(chunk_embeddings.shape)
58
+
59
+ # Return the chunk_embeddings
60
+ return chunk_embeddings
61
+
62
+ # Call the create_embeddings function and store the result in a new chunk_embeddings variable
63
+ chunk_embeddings = create_embeddings(cleaned_chunks) # Complete this line
64
+
65
+ ###STEP 5
66
+ # Define a function to find the most relevant text chunks for a given query, chunk_embeddings, and text_chunks
67
+ def get_top_chunks(query, chunk_embeddings, text_chunks):
68
+ # Convert the query text into a vector embedding
69
+ query_embedding = model.encode(query, convert_to_tensor = True) # Complete this line
70
+
71
+ # Normalize the query embedding to unit length for accurate similarity comparison
72
+ query_embedding_normalized = query_embedding / query_embedding.norm()
73
+
74
+ # Normalize all chunk embeddings to unit length for consistent comparison
75
+ chunk_embeddings_normalized = chunk_embeddings / chunk_embeddings.norm(dim=1, keepdim=True)
76
+
77
+ # Calculate cosine similarity between query and all chunks using matrix multiplication
78
+ similarities = torch.matmul(chunk_embeddings_normalized, query_embedding_normalized) # Complete this line
79
+
80
+ # Print the similarities
81
+ print(similarities)
82
+
83
+ # Find the indices of the 3 chunks with highest similarity scores
84
+ top_indices = torch.topk(similarities, k=3).indices
85
+
86
+ # Print the top indices
87
+ print(top_indices)
88
+
89
+ # Create an empty list to store the most relevant chunks
90
+ top_chunks = []
91
+
92
+ # Loop through the top indices and retrieve the corresponding text chunks
93
+ for i in top_indices:
94
+ relevant_info = cleaned_chunks[i]
95
+ top_chunks.append(relevant_info)
96
+
97
+ # Return the list of most relevant chunks
98
+ return top_chunks
99
+
100
+
101
+ # Print the top results
102
+ print(top_results)
103
 
104
  #AI API being used
105
  client= InferenceClient("Qwen/Qwen2.5-7B-Instruct-1M")
 
117
  response=client.chat_completion(messages, max_tokens=100) #capping how many words the LLM is allowed to generate as a respond (100 words)
118
 
119
  return response['choices'][0]['message']['content'].strip() #storing value of response in a readable format to display
120
+
121
+ ### STEP 6
122
+ # Call the preprocess_text function and store the result in a cleaned_chunks variable
123
+ cleaned_chunks = preprocess_text(poverty_and_education) # Complete this line
124
+ top_results = get_top_chunks("How does poverty affect one's education?", chunk_embeddings, cleaned_chunks) # Complete this line
125
+
126
+ print(top_results)
127
 
128
  #Defining chatbot giving user a UI to interact, see their conversation history, and see new messages using built in gr feature
129
  #ChatInterface requires at least one parameter(a function)