Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,26 +3,27 @@ from sentence_transformers import SentenceTransformer
|
|
| 3 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 4 |
import numpy as np
|
| 5 |
import tempfile
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 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 |
-
#
|
| 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:
|
| 27 |
chunk_embeddings = embedding_model.encode(knowledge_chunks)
|
| 28 |
status = f"✅ Loaded {len(knowledge_chunks)} knowledge chunks"
|
|
@@ -30,7 +31,8 @@ def create_chatbot(role, context, info, conv_starter, file):
|
|
| 30 |
status = "❌ File is empty"
|
| 31 |
else:
|
| 32 |
status = "⚠️ No file uploaded"
|
| 33 |
-
|
|
|
|
| 34 |
return status, {
|
| 35 |
"role": role,
|
| 36 |
"context": context,
|
|
@@ -41,52 +43,47 @@ def create_chatbot(role, context, info, conv_starter, file):
|
|
| 41 |
}
|
| 42 |
|
| 43 |
def respond(message, history, state):
|
| 44 |
-
#
|
| 45 |
if any(keyword in message.lower() for keyword in ["more info", "contact", "information", "email", "details"]):
|
| 46 |
return state["info"]
|
| 47 |
-
|
| 48 |
-
#
|
| 49 |
if not state.get("knowledge"):
|
| 50 |
return "⚠️ Please upload knowledge base first"
|
| 51 |
-
|
| 52 |
-
#
|
| 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 |
-
#
|
| 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")
|
| 66 |
gr.Markdown("Configure every aspect of your chatbot below")
|
| 67 |
-
|
| 68 |
with gr.Row():
|
| 69 |
with gr.Column(scale=1):
|
| 70 |
gr.Markdown("## Configuration Panel")
|
| 71 |
-
|
| 72 |
with gr.Group():
|
| 73 |
-
role = gr.Textbox(label="Role",
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 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 |
-
|
| 90 |
gr.Markdown("### Instructions")
|
| 91 |
gr.Markdown("1. Configure all fields\n2. Upload knowledge file\n3. Click 'Create Chatbot'\n4. Chat in the right panel")
|
| 92 |
|
|
@@ -95,17 +92,15 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
|
|
| 95 |
state = gr.State({})
|
| 96 |
chatbot = gr.ChatInterface(
|
| 97 |
respond,
|
| 98 |
-
chatbot=gr.Chatbot(
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
undo_btn=None,
|
| 106 |
-
clear_btn="Clear History"
|
| 107 |
)
|
| 108 |
-
|
| 109 |
create_btn.click(
|
| 110 |
create_chatbot,
|
| 111 |
inputs=[role, context, info, conv_starter, file],
|
|
|
|
| 3 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 4 |
import numpy as np
|
| 5 |
import tempfile
|
| 6 |
+
import os
|
| 7 |
|
| 8 |
+
# Load embedding model
|
| 9 |
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 10 |
|
| 11 |
def create_chatbot(role, context, info, conv_starter, file):
|
| 12 |
knowledge_chunks = []
|
| 13 |
chunk_embeddings = None
|
| 14 |
+
|
| 15 |
if file:
|
| 16 |
+
# Save uploaded file to a temp file
|
| 17 |
with tempfile.NamedTemporaryFile(delete=False) as temp:
|
| 18 |
temp.write(file.read())
|
| 19 |
temp_path = temp.name
|
| 20 |
+
|
| 21 |
with open(temp_path, 'r', encoding='utf-8') as f:
|
| 22 |
text = f.read()
|
| 23 |
os.unlink(temp_path)
|
| 24 |
+
|
| 25 |
knowledge_chunks = [chunk.strip() for chunk in text.split('\n\n') if chunk.strip()]
|
| 26 |
+
|
| 27 |
if knowledge_chunks:
|
| 28 |
chunk_embeddings = embedding_model.encode(knowledge_chunks)
|
| 29 |
status = f"✅ Loaded {len(knowledge_chunks)} knowledge chunks"
|
|
|
|
| 31 |
status = "❌ File is empty"
|
| 32 |
else:
|
| 33 |
status = "⚠️ No file uploaded"
|
| 34 |
+
|
| 35 |
+
# Store all chatbot settings and knowledge in a dict (state)
|
| 36 |
return status, {
|
| 37 |
"role": role,
|
| 38 |
"context": context,
|
|
|
|
| 43 |
}
|
| 44 |
|
| 45 |
def respond(message, history, state):
|
| 46 |
+
# Special info queries
|
| 47 |
if any(keyword in message.lower() for keyword in ["more info", "contact", "information", "email", "details"]):
|
| 48 |
return state["info"]
|
| 49 |
+
|
| 50 |
+
# No knowledge base loaded
|
| 51 |
if not state.get("knowledge"):
|
| 52 |
return "⚠️ Please upload knowledge base first"
|
| 53 |
+
|
| 54 |
+
# Embed user query
|
| 55 |
query_embedding = embedding_model.encode([message])
|
| 56 |
similarities = cosine_similarity(query_embedding, state["embeddings"])[0]
|
| 57 |
max_index = np.argmax(similarities)
|
| 58 |
max_similarity = similarities[max_index]
|
| 59 |
+
|
| 60 |
+
# If similar enough, return the best chunk
|
| 61 |
if max_similarity > 0.45:
|
| 62 |
return state["knowledge"][max_index]
|
| 63 |
+
|
| 64 |
+
# Fallback
|
| 65 |
return f"{state['role']}\n{state['context']}\nI can't help with that specific question."
|
| 66 |
|
| 67 |
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 68 |
gr.Markdown("# 🤖 Custom Chatbot Creator")
|
| 69 |
gr.Markdown("Configure every aspect of your chatbot below")
|
| 70 |
+
|
| 71 |
with gr.Row():
|
| 72 |
with gr.Column(scale=1):
|
| 73 |
gr.Markdown("## Configuration Panel")
|
| 74 |
+
|
| 75 |
with gr.Group():
|
| 76 |
+
role = gr.Textbox(label="Role", value="AI Assistant specialized in technical queries")
|
| 77 |
+
context = gr.Textbox(label="Context", value="Focus on providing concise, accurate answers based on the knowledge base")
|
| 78 |
+
info = gr.Textbox(label="Contact Info", value="For more information, contact support@example.com")
|
| 79 |
+
conv_starter = gr.Textbox(label="Conversation Starter", value="Ask me about topics in the knowledge base")
|
| 80 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
with gr.Group():
|
| 82 |
+
file = gr.File(label="Knowledge Base (.txt only)", file_types=[".txt"], type="binary")
|
|
|
|
|
|
|
| 83 |
create_btn = gr.Button("Create Chatbot", variant="primary")
|
| 84 |
+
|
| 85 |
status = gr.Textbox(label="Status", interactive=False)
|
| 86 |
+
|
| 87 |
gr.Markdown("### Instructions")
|
| 88 |
gr.Markdown("1. Configure all fields\n2. Upload knowledge file\n3. Click 'Create Chatbot'\n4. Chat in the right panel")
|
| 89 |
|
|
|
|
| 92 |
state = gr.State({})
|
| 93 |
chatbot = gr.ChatInterface(
|
| 94 |
respond,
|
| 95 |
+
chatbot=gr.Chatbot(
|
| 96 |
+
height=500,
|
| 97 |
+
type="messages", # Use OpenAI-style messages for future compatibility
|
| 98 |
+
avatar_images=(None, (None, "https://i.imgur.com/7kQEsHU.png"))
|
| 99 |
+
),
|
| 100 |
+
textbox=gr.Textbox(placeholder="Type your message...", container=False, autofocus=True),
|
| 101 |
+
submit_btn="Ask"
|
|
|
|
|
|
|
| 102 |
)
|
| 103 |
+
|
| 104 |
create_btn.click(
|
| 105 |
create_chatbot,
|
| 106 |
inputs=[role, context, info, conv_starter, file],
|