Shriharsh commited on
Commit
2a28b9c
·
verified ·
1 Parent(s): e367093

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -10
app.py CHANGED
@@ -5,7 +5,7 @@ from transformers import pipeline
5
  from sentence_transformers import SentenceTransformer, util
6
  import PyPDF2
7
 
8
- # Set up logging: we write logs to /tmp so that it's writable on Spaces.
9
  log_file_path = "/tmp/support_bot_log.txt"
10
  logging.basicConfig(filename=log_file_path, level=logging.INFO, format='%(asctime)s - %(message)s')
11
 
@@ -45,7 +45,7 @@ class SupportBotAgent:
45
 
46
  def find_relevant_section(self, query):
47
  """
48
- First uses semantic similarity. If similarity is too low, falls back to a keyword search.
49
  """
50
  stopwords = {"and", "the", "is", "for", "to", "a", "an", "of", "in", "on", "at", "with", "by", "it", "as", "so", "what"}
51
  query_embedding = self.embedder.encode(query, convert_to_tensor=True)
@@ -65,10 +65,10 @@ class SupportBotAgent:
65
  section_words = {word for word in section.lower().split() if word not in stopwords}
66
  common_words = query_words.intersection(section_words)
67
  if len(common_words) >= 2:
68
- logging.info(f"Keyword match found for query: {query} with common words: {common_words}")
69
  return section
70
 
71
- logging.info(f"No good keyword match found. Returning default fallback response.")
72
  return "I don’t have enough information to answer that."
73
 
74
  def answer_query(self, query):
@@ -82,7 +82,7 @@ class SupportBotAgent:
82
  return answer
83
 
84
  def adjust_response(self, query, response, feedback):
85
- """Modify the response based on user feedback."""
86
  if feedback == "too vague":
87
  context = self.find_relevant_section(query)
88
  adjusted_response = f"{response}\n\n(More details:\n{context[:500]}...)"
@@ -96,18 +96,28 @@ class SupportBotAgent:
96
  # --- Gradio Functions and App Workflow ---
97
 
98
  def process_file(file, state):
99
- """Handles the file upload and initializes the SupportBotAgent."""
 
100
  if file is None:
101
  logging.info("No file uploaded")
102
  return [("Bot", "Please upload a TXT or PDF file.")], state
103
- # Save the uploaded file to /tmp
 
104
  temp_path = os.path.join("/tmp", file.name)
105
  with open(temp_path, "wb") as f:
106
- f.write(file.read())
 
 
 
 
 
 
 
107
  try:
108
  state["agent"] = SupportBotAgent(temp_path)
109
  except Exception as e:
110
  return [("Bot", f"Error processing file: {str(e)}")], state
 
111
  state["chat_history"] = [("Bot", "File loaded successfully. Enter your query (or type 'exit' to end):")]
112
  state["mode"] = "query"
113
  state["last_query"] = ""
@@ -117,15 +127,17 @@ def process_file(file, state):
117
 
118
  def process_input(user_input, state):
119
  """
120
- Processes user input as either a query or feedback based on the current mode.
121
  Typing 'exit' stops the session.
122
  """
123
  if state.get("mode", "query") == "ended":
124
  return state["chat_history"], state
 
125
  if user_input.lower() == "exit":
126
  state["chat_history"].append(("Bot", "Session ended. You may now download the log file."))
127
  state["mode"] = "ended"
128
  return state["chat_history"], state
 
129
  if state["mode"] == "query":
130
  state["last_query"] = user_input
131
  answer = state["agent"].answer_query(user_input)
@@ -156,9 +168,10 @@ with gr.Blocks() as demo:
156
  chat = gr.Chatbot()
157
  user_input = gr.Textbox(label="Enter your query or feedback")
158
  submit_btn = gr.Button("Submit")
 
159
  log_file = gr.File(label="Download Log File", file_count="single", interactive=False, value=log_file_path)
160
 
161
  file_upload.upload(process_file, inputs=[file_upload, state], outputs=[chat, state])
162
  submit_btn.click(process_input, inputs=[user_input, state], outputs=[chat, state]).then(lambda: "", None, user_input)
163
 
164
- demo.launch(share=True)
 
5
  from sentence_transformers import SentenceTransformer, util
6
  import PyPDF2
7
 
8
+ # Set up logging: write logs to a writable directory (/tmp)
9
  log_file_path = "/tmp/support_bot_log.txt"
10
  logging.basicConfig(filename=log_file_path, level=logging.INFO, format='%(asctime)s - %(message)s')
11
 
 
45
 
46
  def find_relevant_section(self, query):
47
  """
48
+ Uses semantic similarity first, falling back to keyword search if needed.
49
  """
50
  stopwords = {"and", "the", "is", "for", "to", "a", "an", "of", "in", "on", "at", "with", "by", "it", "as", "so", "what"}
51
  query_embedding = self.embedder.encode(query, convert_to_tensor=True)
 
65
  section_words = {word for word in section.lower().split() if word not in stopwords}
66
  common_words = query_words.intersection(section_words)
67
  if len(common_words) >= 2:
68
+ logging.info(f"Keyword match for query: {query} with common words: {common_words}")
69
  return section
70
 
71
+ logging.info("No good keyword match found. Returning default response.")
72
  return "I don’t have enough information to answer that."
73
 
74
  def answer_query(self, query):
 
82
  return answer
83
 
84
  def adjust_response(self, query, response, feedback):
85
+ """Adjusts the response based on feedback."""
86
  if feedback == "too vague":
87
  context = self.find_relevant_section(query)
88
  adjusted_response = f"{response}\n\n(More details:\n{context[:500]}...)"
 
96
  # --- Gradio Functions and App Workflow ---
97
 
98
  def process_file(file, state):
99
+ """Handles file upload and initializes the SupportBotAgent."""
100
+ logging.info("Received file upload request")
101
  if file is None:
102
  logging.info("No file uploaded")
103
  return [("Bot", "Please upload a TXT or PDF file.")], state
104
+
105
+ # Save the uploaded file to /tmp. Handle both file objects and NamedString.
106
  temp_path = os.path.join("/tmp", file.name)
107
  with open(temp_path, "wb") as f:
108
+ if hasattr(file, "read"):
109
+ content = file.read()
110
+ else:
111
+ content = file
112
+ if isinstance(content, str):
113
+ content = content.encode("utf-8")
114
+ f.write(content)
115
+
116
  try:
117
  state["agent"] = SupportBotAgent(temp_path)
118
  except Exception as e:
119
  return [("Bot", f"Error processing file: {str(e)}")], state
120
+
121
  state["chat_history"] = [("Bot", "File loaded successfully. Enter your query (or type 'exit' to end):")]
122
  state["mode"] = "query"
123
  state["last_query"] = ""
 
127
 
128
  def process_input(user_input, state):
129
  """
130
+ Processes user input: as a query or feedback.
131
  Typing 'exit' stops the session.
132
  """
133
  if state.get("mode", "query") == "ended":
134
  return state["chat_history"], state
135
+
136
  if user_input.lower() == "exit":
137
  state["chat_history"].append(("Bot", "Session ended. You may now download the log file."))
138
  state["mode"] = "ended"
139
  return state["chat_history"], state
140
+
141
  if state["mode"] == "query":
142
  state["last_query"] = user_input
143
  answer = state["agent"].answer_query(user_input)
 
168
  chat = gr.Chatbot()
169
  user_input = gr.Textbox(label="Enter your query or feedback")
170
  submit_btn = gr.Button("Submit")
171
+ # Provide a file component to download the log file
172
  log_file = gr.File(label="Download Log File", file_count="single", interactive=False, value=log_file_path)
173
 
174
  file_upload.upload(process_file, inputs=[file_upload, state], outputs=[chat, state])
175
  submit_btn.click(process_input, inputs=[user_input, state], outputs=[chat, state]).then(lambda: "", None, user_input)
176
 
177
+ demo.launch(share=True)