Anchal23 commited on
Commit
374b382
·
verified ·
1 Parent(s): 6029f08

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -24
app.py CHANGED
@@ -2,22 +2,25 @@ import gradio as gr
2
  from sentence_transformers import SentenceTransformer
3
  from sklearn.metrics.pairwise import cosine_similarity
4
  import numpy as np
5
- import os
6
 
7
  # Initialize embedding model
8
  embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
9
- knowledge_chunks = []
10
- chunk_embeddings = None
11
 
12
  def create_chatbot(role, context, info, conv_starter, file):
13
- global knowledge_chunks, chunk_embeddings
14
  knowledge_chunks = []
15
  chunk_embeddings = None
16
 
17
- # Load knowledge if file provided
18
  if file:
19
- with open(file.name, 'r', encoding='utf-8') as f:
 
 
 
 
 
20
  text = f.read()
 
 
21
  knowledge_chunks = [chunk.strip() for chunk in text.split('\n\n') if chunk.strip()]
22
 
23
  if knowledge_chunks:
@@ -28,28 +31,35 @@ def create_chatbot(role, context, info, conv_starter, file):
28
  else:
29
  status = "⚠️ No file uploaded"
30
 
31
- return status, role, context, info, conv_starter
 
 
 
 
 
 
 
32
 
33
- def respond(message, history, role, context, info):
34
  # Check for information requests
35
  if any(keyword in message.lower() for keyword in ["more info", "contact", "information", "email", "details"]):
36
- return info
37
 
38
  # Handle empty knowledge base
39
- if not knowledge_chunks:
40
  return "⚠️ Please upload knowledge base first"
41
 
42
  # Process query
43
  query_embedding = embedding_model.encode([message])
44
- similarities = cosine_similarity(query_embedding, chunk_embeddings)[0]
45
  max_index = np.argmax(similarities)
46
  max_similarity = similarities[max_index]
47
 
48
  # Return best match if above threshold
49
  if max_similarity > 0.45:
50
- return knowledge_chunks[max_index]
51
 
52
- return "I can't help with that"
53
 
54
  with gr.Blocks(theme=gr.themes.Soft()) as app:
55
  gr.Markdown("# 🤖 Custom Chatbot Creator")
@@ -60,14 +70,20 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
60
  gr.Markdown("## Configuration Panel")
61
 
62
  with gr.Group():
63
- role = gr.Textbox(label="Role", value="You are an assistant helpful for LLM prompting")
64
- context = gr.Textbox(label="Context", value="You search for vector databases for information about prompt engineering and provide short answers.")
65
- info = gr.Textbox(label="Contact Info", value="If someone asks where to find more information, tell them to contact Anchal Kumar Tarwey at email: anchalkumartarwey@gmail.com")
66
- conv_starter = gr.Textbox(label="Conversation Starter", value="What are the three basic LLM prompting concepts?")
 
 
 
 
67
 
68
  with gr.Group():
69
- file = gr.File(label="Knowledge Base (.txt only)", file_types=[".txt"])
70
- create_btn = gr.Button("Create Chatbot")
 
 
71
 
72
  status = gr.Textbox(label="Status", interactive=False)
73
 
@@ -76,10 +92,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
76
 
77
  with gr.Column(scale=2):
78
  gr.Markdown("## Chat Interface")
 
79
  chatbot = gr.ChatInterface(
80
- lambda m, h: respond(m, h, role.value, context.value, info.value),
81
- chatbot=gr.Chatbot(height=400, avatar_images=("user.png", "bot.png")),
82
- textbox=gr.Textbox(placeholder="Type your message...", container=False),
 
 
 
83
  submit_btn="Ask",
84
  retry_btn=None,
85
  undo_btn=None,
@@ -89,8 +109,8 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
89
  create_btn.click(
90
  create_chatbot,
91
  inputs=[role, context, info, conv_starter, file],
92
- outputs=[status, role, context, info, conv_starter]
93
  )
94
 
95
  if __name__ == "__main__":
96
- app.launch()
 
2
  from sentence_transformers import SentenceTransformer
3
  from sklearn.metrics.pairwise import cosine_similarity
4
  import numpy as np
5
+ import tempfile
6
 
7
  # Initialize embedding model
8
  embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
 
 
9
 
10
  def create_chatbot(role, context, info, conv_starter, file):
 
11
  knowledge_chunks = []
12
  chunk_embeddings = None
13
 
 
14
  if file:
15
+ # Use tempfile to handle uploaded file
16
+ with tempfile.NamedTemporaryFile(delete=False) as temp:
17
+ temp.write(file.read())
18
+ temp_path = temp.name
19
+
20
+ with open(temp_path, 'r', encoding='utf-8') as f:
21
  text = f.read()
22
+ os.unlink(temp_path)
23
+
24
  knowledge_chunks = [chunk.strip() for chunk in text.split('\n\n') if chunk.strip()]
25
 
26
  if knowledge_chunks:
 
31
  else:
32
  status = "⚠️ No file uploaded"
33
 
34
+ return status, {
35
+ "role": role,
36
+ "context": context,
37
+ "info": info,
38
+ "conv_starter": conv_starter,
39
+ "knowledge": knowledge_chunks,
40
+ "embeddings": chunk_embeddings
41
+ }
42
 
43
+ def respond(message, history, state):
44
  # Check for information requests
45
  if any(keyword in message.lower() for keyword in ["more info", "contact", "information", "email", "details"]):
46
+ return state["info"]
47
 
48
  # Handle empty knowledge base
49
+ if not state.get("knowledge"):
50
  return "⚠️ Please upload knowledge base first"
51
 
52
  # Process query
53
  query_embedding = embedding_model.encode([message])
54
+ similarities = cosine_similarity(query_embedding, state["embeddings"])[0]
55
  max_index = np.argmax(similarities)
56
  max_similarity = similarities[max_index]
57
 
58
  # Return best match if above threshold
59
  if max_similarity > 0.45:
60
+ return state["knowledge"][max_index]
61
 
62
+ return f"{state['role']}\n{state['context']}\nI can't help with that specific question."
63
 
64
  with gr.Blocks(theme=gr.themes.Soft()) as app:
65
  gr.Markdown("# 🤖 Custom Chatbot Creator")
 
70
  gr.Markdown("## Configuration Panel")
71
 
72
  with gr.Group():
73
+ role = gr.Textbox(label="Role",
74
+ value="AI Assistant specialized in technical queries")
75
+ context = gr.Textbox(label="Context",
76
+ value="Focus on providing concise, accurate answers based on the knowledge base")
77
+ info = gr.Textbox(label="Contact Info",
78
+ value="For more information, contact support@example.com")
79
+ conv_starter = gr.Textbox(label="Conversation Starter",
80
+ value="Ask me about topics in the knowledge base")
81
 
82
  with gr.Group():
83
+ file = gr.File(label="Knowledge Base (.txt only)",
84
+ file_types=[".txt"],
85
+ type="binary")
86
+ create_btn = gr.Button("Create Chatbot", variant="primary")
87
 
88
  status = gr.Textbox(label="Status", interactive=False)
89
 
 
92
 
93
  with gr.Column(scale=2):
94
  gr.Markdown("## Chat Interface")
95
+ state = gr.State({})
96
  chatbot = gr.ChatInterface(
97
+ respond,
98
+ chatbot=gr.Chatbot(height=500,
99
+ avatar_images=(None, (None, "https://i.imgur.com/7kQEsHU.png"))),
100
+ textbox=gr.Textbox(placeholder="Type your message...",
101
+ container=False,
102
+ autofocus=True),
103
  submit_btn="Ask",
104
  retry_btn=None,
105
  undo_btn=None,
 
109
  create_btn.click(
110
  create_chatbot,
111
  inputs=[role, context, info, conv_starter, file],
112
+ outputs=[status, state]
113
  )
114
 
115
  if __name__ == "__main__":
116
+ app.launch()