Spaces:
Runtime error
Runtime error
spotify please please please work
Browse files4 unmodified lines5678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152538 unmodified lines6263646566676869707172733 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610 unmodified lines1171181191201211221231244 unmodified linesimport numpy as npimport requests#LLM we are usingclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta")#adding text filewith open("be_a_better_you.txt", "r", encoding="utf-8") as file1, open("journal_prompts.txt", "r", encoding="utf-8") as file2, open("workout.txt", "r", encoding="utf-8") as file3:wellness_text = file1.read() + "\n" + file2.read() +"\n" + file3.read()#cleaning up the textcleaned_text = wellness_text.strip()chunks = cleaned_text.split("\n")cleaned_chunks = []#putting text in chunksfor chunk in chunks:stripped_chunk = chunk.strip()if stripped_chunk:cleaned_chunks.append(stripped_chunk)#import model for embeddingsmodel = SentenceTransformer('all-MiniLM-L6-v2')chunk_embeddings = model.encode(cleaned_chunks, convert_to_tensor=True)def get_top_chunks(query):# creating a function taking query as my parameterquery_embedding = model.encode(query, convert_to_tensor=True)# encode query to vector embedding for comparisonquery_embedding_normalized = query_embedding / query_embedding.norm()# normalize query to 1: allows for comparison of meaningchunk_embeddings_normalized = chunk_embeddings / chunk_embeddings.norm(dim=1, keepdim=True)# normalizing chunks for comparison of meaningsimilarities = torch.matmul(chunk_embeddings_normalized, query_embedding_normalized)# using matmul (matrix multiplication) method to compare query to chunkstop_indices = torch.topk(similarities, k=3).indices# get the indices of the chunks thart are most similar to my querytop_chunks = []for i in top_indices:chunk = cleaned_chunks[i]# for each index number in top_indices, get back the texttop_chunks.append(chunk)return top_chunksdef get_nutrition_info(food_query):8 unmodified lines}response = requests.post(url, headers=headers, json=body)if response.status_code == 200:data = response.json()return dataelse:return Nonedef get_motivational_quote():url = "https://zenquotes.io/api/random"response = requests.get(url)3 unmodified lineselse:return "Keep going! You're doing great."def respond(message, history):messages = [{"role": "system","content": "You are a big sister chatbot named Nessie. You help people feel better in a simple manner. Always reply in 3 sentences or less. Do NOT stop mid-sentence, as you may confuse them even more. When the user is asking for ideas give 5 max, as you don't want to overwhelm them"}]# change the personalitycontext = get_top_chunks(message)if history:messages.extend(history)messages.append({"role": "user", "content": message})user_context = f"{message}\nInformation: {context}"messages.append({"role": "user", "content": user_context})response = ""for messages in client.chat_completion(messages,max_tokens = 250,stream = True,):token = messages.choices[0].delta.contentresponse+= tokenyield responsetheme = gr.themes.Soft(10 unmodified linesexamples=["Can you help me with my dietary goals? I want to track my calories, macros, and get advice based on myself.","Can you help me reach my fitness goals? I would like guidance and recommendations on workouts based on my goals.","Can you give me some journal prompts? I want to start journaling to help myself reflect on my goals and have some daily affirmations. "])#chatbot = gr.ChatInterface(respond, type = 'messages', title= "Hi! I'm Nessie, your personal wellness assistant. What can I assist you with today?",examples=["Can I help you with your dietary goals? I can help you track your calories, macros, and give advice based on personal goals, height, and weight.","Can I help you with your physical health and help you reach your fitness goals? I can give guidance and recommendations for specific workouts based on personal goals.","If you are struggling, I am here. You are so beautiful and so loved! I'm here for whatever you need. "])demo.launch(debug=True)4 unmodified lines567891011121314151617181920212223242526272829303132338 unmodified lines424344454647484950513 unmodified lines55565758596061626364656667686970717273747576777879808110 unmodified lines92939495969798991001011021031041051061071081091101111121131141154 unmodified linesimport numpy as npimport requests# LLM we are usingclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta")# adding text fileswith open("be_a_better_you.txt", "r", encoding="utf-8") as file1, open("journal_prompts.txt", "r", encoding="utf-8") as file2, open("workout.txt", "r", encoding="utf-8") as file3:wellness_text = file1.read() + "\n" + file2.read() + "\n" + file3.read()# cleaning up the textcleaned_text = wellness_text.strip()chunks = cleaned_text.split("\n")cleaned_chunks = [chunk.strip() for chunk in chunks if chunk.strip()]# import model for embeddingsmodel = SentenceTransformer('all-MiniLM-L6-v2')chunk_embeddings = model.encode(cleaned_chunks, convert_to_tensor=True)def get_top_chunks(query):query_embedding = model.encode(query, convert_to_tensor=True)query_embedding_normalized = query_embedding / query_embedding.norm()chunk_embeddings_normalized = chunk_embeddings / chunk_embeddings.norm(dim=1, keepdim=True)similarities = torch.matmul(chunk_embeddings_normalized, query_embedding_normalized)top_indices = torch.topk(similarities, k=3).indicestop_chunks = [cleaned_chunks[i] for i in top_indices]return top_chunksdef get_nutrition_info(food_query):8 unmodified lines}response = requests.post(url, headers=headers, json=body)if response.status_code == 200:return response.json()else:return Nonedef get_motivational_quote():url = "https://zenquotes.io/api/random"response = requests.get(url)3 unmodified lineselse:return "Keep going! You're doing great."def respond(message, history):messages = [{"role": "system","content": "You are a big sister chatbot named Nessie. You help people feel better in a simple manner. Always reply in 3 sentences or less. Do NOT stop mid-sentence, as you may confuse them even more. When the user is asking for ideas give 5 max, as you don't want to overwhelm them"}]context = get_top_chunks(message)if history:messages.extend(history)messages.append({"role": "user", "content": message})user_context = f"{message}\nInformation: {context}"messages.append({"role": "user", "content": user_context})response = ""for messages in client.chat_completion(messages,max_tokens=250,stream=True,):token = messages.choices[0].delta.contentresponse += tokenyield responsetheme = gr.themes.Soft(10 unmodified linesexamples=["Can you help me with my dietary goals? I want to track my calories, macros, and get advice based on myself.","Can you help me reach my fitness goals? I would like guidance and recommendations on workouts based on my goals.","Can you give me some journal prompts? I want to start journaling to help myself reflect on my goals and have some daily affirmations."])with gr.Row():gr.HTML("""<iframe style="border-radius:12px"src="https://open.spotify.com/playlist/5dBkWtszs4KBDjwmpedb66?si=9cc22b91e49446d3&pt=dc6aaab05d72d3056f5891cd2c4e1ce7"width="100%"height="152"frameBorder="0"allowfullscreen=""allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"loading="lazy"></iframe>""")# Launch the appdemo.launch(debug=True)
app.py+31-40