fionasu commited on
Commit
bff002a
·
verified ·
1 Parent(s): 984367c

added code from semantic search

Browse files
Files changed (1) hide show
  1. app.py +103 -0
app.py CHANGED
@@ -1,6 +1,109 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  client = InferenceClient("Qwen/Qwen2.5-72B-Instruct")
5
 
6
  def respond(message, history):
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
4
+ #STEP 1 FROM SEMATIC SEARCH
5
+ from sentence_transformers import SentenceTransformer
6
+ import torch
7
+
8
+ #STEP 2 FROM SEMATIC SEARCH
9
+ # Open the water_cycle.txt file in read mode with UTF-8 encoding
10
+ with open("water_cycle.txt", "r", encoding="utf-8") as file:
11
+ # Read the entire contents of the file and store it in a variable
12
+ water_cycle_text = file.read()
13
+ print(water_cycle_text)
14
+
15
+ #STEP 3 FROM SEMATIC SEARCH
16
+ def preprocess_text(text):
17
+ # Strip extra whitespace from the beginning and the end of the text
18
+ cleaned_text = text.strip()
19
+
20
+ # Split the cleaned_text by every newline character (\n)
21
+ chunks = cleaned_text.split("\n")
22
+
23
+ # Create an empty list to store cleaned chunks
24
+ cleaned_chunks = []
25
+
26
+ # Write your for-in loop below to clean each chunk and add it to the cleaned_chunks list
27
+ for chunk in chunks:
28
+ chunk.strip()
29
+
30
+ if chunk != "":
31
+ cleaned_chunks.append(chunk)
32
+
33
+ # Print cleaned_chunks
34
+ print(cleaned_chunks)
35
+
36
+ # Print the length of cleaned_chunks
37
+ print(len(cleaned_chunks))
38
+
39
+ # Return the cleaned_chunks
40
+ return cleaned_chunks
41
+
42
+ # Call the preprocess_text function and store the result in a cleaned_chunks variable
43
+ cleaned_chunks = preprocess_text(water_cycle_text) # Complete this line
44
+
45
+ #STEP 4 FROM SEMATIC SEARCH
46
+ # Load the pre-trained embedding model that converts text to vectors
47
+ model = SentenceTransformer('all-MiniLM-L6-v2')
48
+
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 FROM SEMATIC SEARCH
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 top_index in top_indices:
94
+ top_chunks.append(text_chunks[top_index])
95
+
96
+ # Return the list of most relevant chunks
97
+ return top_chunks
98
+
99
+ #STEP 6 FROM SEMATIC SEARCH
100
+ # Call the get_top_chunks function with the original query
101
+ top_results = get_top_chunks("How do you make banana bread?", chunk_embeddings, cleaned_chunks)
102
+
103
+ # Print the top results
104
+ print(top_results)
105
+
106
+
107
  client = InferenceClient("Qwen/Qwen2.5-72B-Instruct")
108
 
109
  def respond(message, history):