NikkiSul commited on
Commit
819fc71
·
verified ·
1 Parent(s): 5505181

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -20
app.py CHANGED
@@ -2,6 +2,7 @@ import gradio as gr
2
  from sentence_transformers import SentenceTransformer, util
3
  import openai
4
  import os
 
5
 
6
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
7
 
@@ -11,7 +12,7 @@ retrieval_model_name = 'output/sentence-transformer-finetuned/'
11
 
12
  openai.api_key = os.environ["OPENAI_API_KEY"]
13
 
14
- system_message = "You use keywords such as modest or not modest,comfort level (1=comfortable, 2=everyday wear, 3=formal), color, and occasion inputted by users and outputting a list of simple clothing pieces (consisting of a top, bottom, and possibly accessories and outerwear) as well as the pinterest link to the outfit created, resulting in a cohesive outfit. Consider season first then consider the other keywords the user inputs."
15
  # Initial system message to set the behavior of the assistant
16
  messages = [{"role": "system", "content": system_message}]
17
 
@@ -37,10 +38,9 @@ def load_and_preprocess_text(filename):
37
 
38
  segments = load_and_preprocess_text(filename)
39
 
40
- def find_relevant_segment(user_query, segments):
41
  """
42
- Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.
43
- This version finds the best match based on the content of the query.
44
  """
45
  try:
46
  # Lowercase the query for better matching
@@ -53,21 +53,24 @@ def find_relevant_segment(user_query, segments):
53
  # Compute cosine similarities between the query and the segments
54
  similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
55
 
56
- # Find the index of the most similar segment
57
- best_idx = similarities.argmax()
58
 
59
- # Return the most relevant segment
60
- return segments[best_idx]
61
  except Exception as e:
62
- print(f"Error in finding relevant segment: {e}")
63
- return ""
64
 
65
- def generate_response(user_query, relevant_segment):
66
  """
67
  Generate a response emphasizing the bot's capability in providing fashion information.
68
  """
69
  try:
70
- user_message = f"Of course! Here are your outfit suggestions and some sustainable brands you can buy from: {relevant_segment}"
 
 
 
71
 
72
  # Append user's message to messages list
73
  messages.append({"role": "user", "content": user_message})
@@ -76,7 +79,7 @@ def generate_response(user_query, relevant_segment):
76
  model="gpt-3.5-turbo",
77
  messages=messages,
78
  max_tokens=150,
79
- temperature=0.3,
80
  top_p=1,
81
  frequency_penalty=0,
82
  presence_penalty=0
@@ -100,17 +103,16 @@ def query_model(question):
100
  """
101
  if question == "":
102
  return "Welcome to Savvy! Use the word bank to describe the outfit you would like generated."
103
- relevant_segment = find_relevant_segment(question, segments)
104
- if not relevant_segment:
105
  return "I'm sorry. Could you be more specific? Check your spelling and make sure to use words from the bank."
106
- response = generate_response(question, relevant_segment)
107
  return response
108
 
109
  # Define the welcome message and specific topics the chatbot can provide information about
110
  welcome_message = """
111
  # 🌷 Welcome to Savvy!
112
-
113
- ## You can ask our SustainaBot to find eco-friendly brands, make outfits based on season and aesthetic, and to learn more about the detriments of fast fashion. You can also learn how to contribute to circular fashion by scrolling down. Created by Sarah, Medha, Nicole, and Tegen of the 2024 Kode With Klossy SEATTLE Camp.
114
  """
115
 
116
  topics = """
@@ -132,7 +134,6 @@ with gr.Blocks(theme='JohnSmith9982/small_and_pretty') as demo:
132
  answer = gr.Textbox(label="Sustainabot Response", placeholder="Sustainabot will respond here...", interactive=False, lines=10)
133
  submit_button = gr.Button("Submit")
134
  submit_button.click(fn=query_model, inputs=question, outputs=answer)
135
-
136
 
137
  # Launch the Gradio app to allow user interaction
138
- demo.launch(share=True)
 
2
  from sentence_transformers import SentenceTransformer, util
3
  import openai
4
  import os
5
+ import random # Import the random library
6
 
7
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
8
 
 
12
 
13
  openai.api_key = os.environ["OPENAI_API_KEY"]
14
 
15
+ system_message = "You put together outfits by taking keywords such as modest or not modest,comfort level (1=comfortable, 2=everyday wear, 3=formal), color, and occasion inputted by users and outputting a list of simple clothing pieces (consisting of a top, bottom, and possibly accessories and outerwear) and a Pinterest link to the outfit created, resulting in a cohesive outfit."
16
  # Initial system message to set the behavior of the assistant
17
  messages = [{"role": "system", "content": system_message}]
18
 
 
38
 
39
  segments = load_and_preprocess_text(filename)
40
 
41
+ def find_relevant_segments(user_query, segments):
42
  """
43
+ Find the most relevant text segments for a user's query using cosine similarity among sentence embeddings.
 
44
  """
45
  try:
46
  # Lowercase the query for better matching
 
53
  # Compute cosine similarities between the query and the segments
54
  similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
55
 
56
+ # Get indices of the most similar segments
57
+ best_indices = similarities.topk(5).indices.tolist()
58
 
59
+ # Return the most relevant segments
60
+ return [segments[idx] for idx in best_indices]
61
  except Exception as e:
62
+ print(f"Error in finding relevant segments: {e}")
63
+ return []
64
 
65
+ def generate_response(user_query, relevant_segments):
66
  """
67
  Generate a response emphasizing the bot's capability in providing fashion information.
68
  """
69
  try:
70
+ # Randomly select an outfit from the relevant segments
71
+ random_segment = random.choice(relevant_segments)
72
+
73
+ user_message = f"Of course! Here are your outfit suggestions and some sustainable brands you can buy from: {random_segment}"
74
 
75
  # Append user's message to messages list
76
  messages.append({"role": "user", "content": user_message})
 
79
  model="gpt-3.5-turbo",
80
  messages=messages,
81
  max_tokens=150,
82
+ temperature=0.4,
83
  top_p=1,
84
  frequency_penalty=0,
85
  presence_penalty=0
 
103
  """
104
  if question == "":
105
  return "Welcome to Savvy! Use the word bank to describe the outfit you would like generated."
106
+ relevant_segments = find_relevant_segments(question, segments)
107
+ if not relevant_segments:
108
  return "I'm sorry. Could you be more specific? Check your spelling and make sure to use words from the bank."
109
+ response = generate_response(question, relevant_segments)
110
  return response
111
 
112
  # Define the welcome message and specific topics the chatbot can provide information about
113
  welcome_message = """
114
  # 🌷 Welcome to Savvy!
115
+ ## You can ask our SustainaBot to find eco-friendly brands, make outfits based on season and aesthetic, and to learn more about the detriments of fast fashion. You can also learn how to contribute to circular fashion by scrolling down. Created by Sarah, Medha, Nicole, and Tegen of the 2024 Kode With Klossy CITY Camp.
 
116
  """
117
 
118
  topics = """
 
134
  answer = gr.Textbox(label="Sustainabot Response", placeholder="Sustainabot will respond here...", interactive=False, lines=10)
135
  submit_button = gr.Button("Submit")
136
  submit_button.click(fn=query_model, inputs=question, outputs=answer)
 
137
 
138
  # Launch the Gradio app to allow user interaction
139
+ demo.launch(share=True)