Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,101 @@
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
""
|
7 |
-
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
)
|
37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
-
|
40 |
-
yield response
|
41 |
-
|
42 |
-
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
-
demo = gr.ChatInterface(
|
47 |
-
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
-
)
|
61 |
-
|
62 |
-
|
63 |
-
if __name__ == "__main__":
|
64 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
import os
|
3 |
+
from langchain.document_loaders import PyPDFLoader
|
4 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
5 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
6 |
+
from langchain.vectorstores import FAISS
|
7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
8 |
|
9 |
+
# Configuration
|
10 |
+
DOCS_DIR = "business_docs"
|
11 |
+
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
12 |
+
MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.1"
|
13 |
|
14 |
+
# Initialize components once at startup
|
15 |
+
def initialize_system():
|
16 |
+
# Load and process PDFs from business_docs folder
|
17 |
+
if not os.path.exists(DOCS_DIR):
|
18 |
+
raise FileNotFoundError(f"Business documents folder '{DOCS_DIR}' not found")
|
19 |
+
|
20 |
+
pdf_files = [os.path.join(DOCS_DIR, f) for f in os.listdir(DOCS_DIR) if f.endswith(".pdf")]
|
21 |
+
if not pdf_files:
|
22 |
+
raise ValueError(f"No PDF files found in {DOCS_DIR} folder")
|
23 |
|
24 |
+
# Process documents
|
25 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
26 |
+
chunk_size=1000,
|
27 |
+
chunk_overlap=200
|
28 |
+
)
|
29 |
+
|
30 |
+
texts = []
|
31 |
+
for pdf in pdf_files:
|
32 |
+
loader = PyPDFLoader(pdf)
|
33 |
+
pages = loader.load_and_split(text_splitter)
|
34 |
+
texts.extend(pages)
|
35 |
|
36 |
+
# Create vector store
|
37 |
+
embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
|
38 |
+
vector_store = FAISS.from_documents(texts, embeddings)
|
39 |
+
|
40 |
+
# Load model with quantization for faster inference
|
41 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
42 |
+
model = AutoModelForCausalLM.from_pretrained(
|
43 |
+
MODEL_NAME,
|
44 |
+
device_map="auto",
|
45 |
+
load_in_8bit=True
|
46 |
+
)
|
47 |
+
|
48 |
+
return vector_store, model, tokenizer
|
49 |
|
50 |
+
# Initialize system components
|
51 |
+
try:
|
52 |
+
vector_store, model, tokenizer = initialize_system()
|
53 |
+
print("System initialized successfully with business documents")
|
54 |
+
except Exception as e:
|
55 |
+
print(f"Initialization error: {str(e)}")
|
56 |
+
raise
|
57 |
|
58 |
+
# Response generation with context
|
59 |
+
def generate_response(query):
|
60 |
+
# Retrieve relevant context
|
61 |
+
docs = vector_store.similarity_search(query, k=3)
|
62 |
+
context = "\n".join([doc.page_content for doc in docs])
|
63 |
+
|
64 |
+
# Create instruction prompt
|
65 |
+
prompt = f"""<s>[INST] You are a customer support agent.
|
66 |
+
Answer ONLY using information from the provided business documents.
|
67 |
+
If unsure, say "I don't have information about that."
|
68 |
+
|
69 |
+
Context: {context}
|
70 |
+
Question: {query} [/INST]"""
|
71 |
+
|
72 |
+
# Generate response
|
73 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
74 |
+
outputs = model.generate(
|
75 |
+
**inputs,
|
76 |
+
max_new_tokens=500,
|
77 |
+
temperature=0.3,
|
78 |
+
do_sample=True
|
79 |
+
)
|
80 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True).split("[/INST]")[-1].strip()
|
81 |
|
82 |
+
# Chat interface
|
83 |
+
with gr.Blocks() as demo:
|
84 |
+
gr.Markdown("## Business Support Chatbot\nAsk questions about our services!")
|
85 |
+
|
86 |
+
chatbot = gr.Chatbot(label="Conversation")
|
87 |
+
msg = gr.Textbox(label="Type your question")
|
88 |
+
clear = gr.Button("Clear History")
|
89 |
+
|
90 |
+
def respond(message, chat_history):
|
91 |
+
try:
|
92 |
+
response = generate_response(message)
|
93 |
+
except Exception as e:
|
94 |
+
response = "Sorry, I'm having trouble answering right now. Please try again later."
|
95 |
+
chat_history.append((message, response))
|
96 |
+
return "", chat_history
|
97 |
+
|
98 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
99 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
100 |
|
101 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|