Aarnaburji commited on
Commit
22e0a37
·
verified ·
1 Parent(s): a9fdeca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -12
app.py CHANGED
@@ -8,7 +8,11 @@ os.environ["TOKENIZERS_PARALLELISM"] = "false"
8
  # Initialize paths and model identifiers for easy configuration and maintenance
9
  filename = "output_topic_details.txt" # Path to the file storing chess-specific details
10
  retrieval_model_name = 'output/sentence-transformer-finetuned/'
11
- path_to_image = "images/san-francisco.jpg" # Update this to the correct path
 
 
 
 
12
 
13
  openai.api_key = os.environ["OPENAI_API_KEY"]
14
 
@@ -24,6 +28,9 @@ except Exception as e:
24
  print(f"Failed to load models: {e}")
25
 
26
  def load_and_preprocess_text(filename):
 
 
 
27
  try:
28
  with open(filename, 'r', encoding='utf-8') as file:
29
  segments = [line.strip() for line in file if line.strip()]
@@ -36,50 +43,83 @@ def load_and_preprocess_text(filename):
36
  segments = load_and_preprocess_text(filename)
37
 
38
  def find_relevant_segment(user_query, segments):
 
 
 
 
39
  try:
 
40
  lower_query = user_query.lower()
 
 
41
  query_embedding = retrieval_model.encode(lower_query)
42
  segment_embeddings = retrieval_model.encode(segments)
 
 
43
  similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
 
 
44
  best_idx = similarities.argmax()
 
 
45
  return segments[best_idx]
46
  except Exception as e:
47
  print(f"Error in finding relevant segment: {e}")
48
  return ""
49
 
50
  def generate_response(user_query, relevant_segment):
 
 
 
51
  try:
52
  user_message = f"Here's the information on outer space: {relevant_segment}"
 
 
53
  messages.append({"role": "user", "content": user_message})
54
 
55
  response = openai.ChatCompletion.create(
56
- model="gpt-4o",
57
  messages=messages,
58
- max_tokens=500,
59
  temperature=0.2,
60
  top_p=1,
61
  frequency_penalty=0,
62
  presence_penalty=0
63
  )
64
 
 
65
  output_text = response['choices'][0]['message']['content'].strip()
 
 
66
  messages.append({"role": "assistant", "content": output_text})
 
67
  return output_text
 
68
  except Exception as e:
69
  print(f"Error in generating response: {e}")
70
  return f"Error in generating response: {e}"
71
 
72
  def query_model(question):
 
 
 
73
  if question == "":
74
- return "Welcome to Starfinder! Ask me anything about outer space, stargazing, and upcoming astronomical events."
 
75
  if "san francisco" in question.lower():
76
- return path_to_image # Return the image path when asked about San Francisco
 
 
 
 
 
77
  relevant_segment = find_relevant_segment(question, segments)
78
  if not relevant_segment:
79
- return "Could not find specific information. Please refine your question."
80
  response = generate_response(question, relevant_segment)
81
- return response
82
 
 
83
  welcome_message = """
84
  # ♟️ Welcome to Starfinder!
85
  ## Your AI-driven assistant for all astronomy-related queries. Created by Aarna, Aditi, and Anastasia of the 2024 Kode With Klossy SF Camp.
@@ -95,21 +135,39 @@ topics = """
95
  - Astronomy tips
96
  """
97
 
98
- with gr.Blocks(theme='JohnSmith9982/small_and_pretty') as demo:
99
- gr.Markdown(welcome_message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  with gr.Row():
101
  with gr.Column():
102
- gr.Markdown(topics)
103
  with gr.Row():
104
  with gr.Column():
105
  question = gr.Textbox(label="Your question", placeholder="What do you want to ask about?")
106
  answer = gr.Textbox(label="StarFinder Response", placeholder="StarFinder will respond here...", interactive=False, lines=10)
 
107
  submit_button = gr.Button("Submit")
108
- submit_button.click(fn=query_model, inputs=question, outputs=answer)
109
- gr.Image(path_to_image).style(display=False) # This will be toggled to display when needed
110
 
 
111
  demo.launch(share=True)
112
 
113
 
114
 
115
 
 
 
 
 
8
  # Initialize paths and model identifiers for easy configuration and maintenance
9
  filename = "output_topic_details.txt" # Path to the file storing chess-specific details
10
  retrieval_model_name = 'output/sentence-transformer-finetuned/'
11
+
12
+ # Define paths to images
13
+ path_to_sf_image = "output/sf.png"
14
+ path_to_sacramento_image = "output/sacramento.png"
15
+ path_to_la_image = "output/la.png"
16
 
17
  openai.api_key = os.environ["OPENAI_API_KEY"]
18
 
 
28
  print(f"Failed to load models: {e}")
29
 
30
  def load_and_preprocess_text(filename):
31
+ """
32
+ Load and preprocess text from a file, removing empty lines and stripping whitespace.
33
+ """
34
  try:
35
  with open(filename, 'r', encoding='utf-8') as file:
36
  segments = [line.strip() for line in file if line.strip()]
 
43
  segments = load_and_preprocess_text(filename)
44
 
45
  def find_relevant_segment(user_query, segments):
46
+ """
47
+ Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.
48
+ This version finds the best match based on the content of the query.
49
+ """
50
  try:
51
+ # Lowercase the query for better matching
52
  lower_query = user_query.lower()
53
+
54
+ # Encode the query and the segments
55
  query_embedding = retrieval_model.encode(lower_query)
56
  segment_embeddings = retrieval_model.encode(segments)
57
+
58
+ # Compute cosine similarities between the query and the segments
59
  similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
60
+
61
+ # Find the index of the most similar segment
62
  best_idx = similarities.argmax()
63
+
64
+ # Return the most relevant segment
65
  return segments[best_idx]
66
  except Exception as e:
67
  print(f"Error in finding relevant segment: {e}")
68
  return ""
69
 
70
  def generate_response(user_query, relevant_segment):
71
+ """
72
+ Generate a response emphasizing the bot's capability in providing astronomical information.
73
+ """
74
  try:
75
  user_message = f"Here's the information on outer space: {relevant_segment}"
76
+
77
+ # Append user's message to messages list
78
  messages.append({"role": "user", "content": user_message})
79
 
80
  response = openai.ChatCompletion.create(
81
+ model="gpt-3.5-turbo",
82
  messages=messages,
83
+ max_tokens=150,
84
  temperature=0.2,
85
  top_p=1,
86
  frequency_penalty=0,
87
  presence_penalty=0
88
  )
89
 
90
+ # Extract the response text
91
  output_text = response['choices'][0]['message']['content'].strip()
92
+
93
+ # Append assistant's message to messages list for context
94
  messages.append({"role": "assistant", "content": output_text})
95
+
96
  return output_text
97
+
98
  except Exception as e:
99
  print(f"Error in generating response: {e}")
100
  return f"Error in generating response: {e}"
101
 
102
  def query_model(question):
103
+ """
104
+ Process a question, find relevant information, and generate a response.
105
+ """
106
  if question == "":
107
+ return "Welcome to Starfinder! Ask me anything about outer space, stargazing, and upcoming astronomical events.", None
108
+
109
  if "san francisco" in question.lower():
110
+ return "Here is a picture of San Francisco!", path_to_sf_image
111
+ if "sacramento" in question.lower():
112
+ return "Here is a picture of Sacramento!", path_to_sacramento_image
113
+ if "los angeles" in question.lower() or "la" in question.lower():
114
+ return "Here is a picture of Los Angeles!", path_to_la_image
115
+
116
  relevant_segment = find_relevant_segment(question, segments)
117
  if not relevant_segment:
118
+ return "Could not find specific information. Please refine your question.", None
119
  response = generate_response(question, relevant_segment)
120
+ return response, None
121
 
122
+ # Define the welcome message and specific topics the chatbot can provide information about
123
  welcome_message = """
124
  # ♟️ Welcome to Starfinder!
125
  ## Your AI-driven assistant for all astronomy-related queries. Created by Aarna, Aditi, and Anastasia of the 2024 Kode With Klossy SF Camp.
 
135
  - Astronomy tips
136
  """
137
 
138
+ STARS = gr.themes.Base().set(
139
+ background_fill_primary='#2A628F', # Light yellow background
140
+ background_fill_primary_dark='#FFD700', # Darker yellow background
141
+ background_fill_secondary='#3E92CC', # Light blue background
142
+ background_fill_secondary_dark='#2A628F', # Darker blue background
143
+ border_color_accent='#16324F', # Accent border color (dark blue)
144
+ border_color_accent_dark='#16324F', # Dark accent border color (dark blue)
145
+ border_color_accent_subdued='#18435A', # Subdued accent border color (slightly lighter blue)
146
+ border_color_primary='#2A628F', # Primary border color (medium blue)
147
+ block_border_color='#2A628F', # Block border color (medium blue)
148
+ button_primary_background_fill='#2A628F', # Primary button background color (medium blue)
149
+ )
150
+
151
+ # Setup the Gradio Blocks interface with custom layout components
152
+ with gr.Blocks(theme=STARS) as demo:
153
+ gr.Markdown(welcome_message) # Display the formatted welcome message
154
  with gr.Row():
155
  with gr.Column():
156
+ gr.Markdown(topics) # Show the topics on the left side
157
  with gr.Row():
158
  with gr.Column():
159
  question = gr.Textbox(label="Your question", placeholder="What do you want to ask about?")
160
  answer = gr.Textbox(label="StarFinder Response", placeholder="StarFinder will respond here...", interactive=False, lines=10)
161
+ image_output = gr.Image(label="Image Output") # Add an Image component
162
  submit_button = gr.Button("Submit")
163
+ submit_button.click(fn=query_model, inputs=question, outputs=[answer, image_output]) # Update outputs to include the image component
 
164
 
165
+ # Launch the Gradio app to allow user interaction
166
  demo.launch(share=True)
167
 
168
 
169
 
170
 
171
+
172
+
173
+