Spaces:
Runtime error
Runtime error
Added Colab Stuff
Browse files12345678import gradio as grimport random#import lines go at the top!from huggingface_hub import InferenceClientclient = InferenceClient("microsoft/phi-4")# name of llm chatbot accessed ^^ or can use ' microsoft/phi-4 that's connected to the microsoft phi gen model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import gradio as grimport randomfrom huggingface_hub import InferenceClient# SEMANTIC SEARCH STEP 1from sentence_transformers import SentenceTransformerimport torch#import lines go at the top!# SEMANTIC SEARCH STEP 2 --> EDIT WITH YOUR OWN KNOWLEDGE BASE WHEN READYwith open("water_cycle.txt", "r", encoding="utf-8") as file:# Read the entire contents of the file and store it in a variablewater_cycle_text = file.read()print(water_cycle_text)# SEMANTIC SEARCH STEP 3def preprocess_text(text):# Strip extra whitespace from the beginning and the end of the textcleaned_text = text.strip()# Split the cleaned_text by every newline character (\n)chunks = cleaned_text.split("\n")# Create an empty list to store cleaned chunkscleaned_chunks = []# Write your for-in loop below to clean each chunk and add it to the cleaned_chunks listfor chunk in chunks:stripped_chunk = chunk.strip()cleaned_chunks.append(stripped_chunk)# Print cleaned_chunksprint(cleaned_chunks)# Print the length of cleaned_chunksprint(len(cleaned_chunks))# Return the cleaned_chunksreturn cleaned_chunks# Call the preprocess_text function and store the result in a cleaned_chunks variablecleaned_chunks = preprocess_text(water_cycle_text) # Complete this line; edit with my knowledgebase when ready# SEMANTIC SEARCH STEP 4# Load the pre-trained embedding model that converts text to vectorsmodel = SentenceTransformer('all-MiniLM-L6-v2')def create_embeddings(text_chunks):# Convert each text chunk into a vector embedding and store as a tensorchunk_embeddings = model.encode(text_chunks, convert_to_tensor=True) # Replace ... with the text_chunks list# Print the chunk embeddingsprint(chunk_embeddings)# Print the shape of chunk_embeddingsprint(chunk_embeddings.shape)# Return the chunk_embeddingsreturn chunk_embeddings# Call the create_embeddings function and store the result in a new chunk_embeddings variablechunk_embeddings = create_embeddings(cleaned_chunks) # Complete this line# SEMANTIC SEARCH STEP 5def get_top_chunks(query, chunk_embeddings, text_chunks):# Convert the query text into a vector embeddingquery_embedding = model.encode(query, convert_to_tensor = True) # Complete this line# Normalize the query embedding to unit length for accurate similarity comparison; bring it to the length of 1query_embedding_normalized = query_embedding / query_embedding.norm()# Normalize all chunk embeddings to unit length for consistent comparisonchunk_embeddings_normalized = chunk_embeddings / chunk_embeddings.norm(dim=1, keepdim=True)# Calculate cosine similarity between query and all chunks using matrix multiplicationsimilarities = torch.matmul(chunk_embeddings_normalized, query_embedding_normalized) # Complete this line# Print the similaritiesprint(similarities)# Find the indices of the 3 chunks with highest similarity scorestop_indices = torch.topk(similarities, k=3).indices# Print the top indicesprint(top_indices)# Create an empty list to store the most relevant chunkstop_chunks = []# Loop through the top indices and retrieve the corresponding text chunksfor i in top_indices:relevant_info = cleaned_chunks[i]top_chunks.append(relevant_info)# Return the list of most relevant chunksreturn top_chunks# SEMANTIC SEARCH STEP 6# Call the get_top_chunks function with the original querytop_results = get_top_chunks('Is water good?',chunk_embeddings, cleaned_chunks) # Complete this lineprint(top_results)# Print the top resultsclient = InferenceClient("microsoft/phi-4")# name of llm chatbot accessed ^^ or can use ' microsoft/phi-4 that's connected to the microsoft phi gen model
app.py+106-1