Spaces:
Runtime error
Runtime error
Gopikanth123
commited on
Update main.py
Browse files
main.py
CHANGED
@@ -1,114 +1,126 @@
|
|
1 |
-
import os
|
2 |
-
import shutil
|
3 |
-
from flask import Flask, render_template, request, jsonify
|
4 |
-
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate, Settings
|
5 |
-
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
|
6 |
-
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
7 |
-
from huggingface_hub import InferenceClient
|
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 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
os.
|
45 |
-
|
46 |
|
47 |
-
|
48 |
-
|
49 |
-
return
|
50 |
|
51 |
-
|
52 |
-
|
53 |
-
print("Persist data cleared and updated with new data.")
|
54 |
-
|
55 |
-
def handle_query(query):
|
56 |
-
chat_text_qa_msgs = [
|
57 |
-
("user", """
|
58 |
-
You are the Taj Hotel chatbot and your name is Taj Hotel Helper. Your goal is to provide accurate, professional, and helpful answers to user queries based on the given Taj hotel's data. Always ensure your responses are clear and concise. Give response within 10-15 words only. You need to give an answer in the same language used by the user.
|
59 |
-
{context_str}
|
60 |
-
Question:
|
61 |
-
{query_str}
|
62 |
-
""")
|
63 |
-
]
|
64 |
-
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
65 |
|
66 |
-
|
67 |
-
index =
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
84 |
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
from flask import Flask, render_template, request, jsonify
|
4 |
+
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate, Settings
|
5 |
+
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
|
6 |
+
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
7 |
+
from huggingface_hub import InferenceClient
|
8 |
+
|
9 |
+
# Ensure HF_TOKEN is set
|
10 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
11 |
+
if not HF_TOKEN:
|
12 |
+
raise ValueError("HF_TOKEN environment variable not set.")
|
13 |
+
|
14 |
+
repo_id = "meta-llama/Meta-Llama-3-8B-Instruct"
|
15 |
+
llm_client = InferenceClient(
|
16 |
+
model=repo_id,
|
17 |
+
token=HF_TOKEN,
|
18 |
+
)
|
19 |
+
|
20 |
+
# Configure Llama index settings
|
21 |
+
Settings.llm = HuggingFaceInferenceAPI(
|
22 |
+
model_name=repo_id,
|
23 |
+
tokenizer_name=repo_id,
|
24 |
+
context_window=3000,
|
25 |
+
token=HF_TOKEN,
|
26 |
+
max_new_tokens=512,
|
27 |
+
generate_kwargs={"temperature": 0.1},
|
28 |
+
)
|
29 |
+
Settings.embed_model = HuggingFaceEmbedding(
|
30 |
+
model_name="BAAI/bge-small-en-v1.5"
|
31 |
+
)
|
32 |
+
|
33 |
+
PERSIST_DIR = "db"
|
34 |
+
PDF_DIRECTORY = 'data'
|
35 |
+
|
36 |
+
# Ensure directories exist
|
37 |
+
os.makedirs(PDF_DIRECTORY, exist_ok=True)
|
38 |
+
os.makedirs(PERSIST_DIR, exist_ok=True)
|
39 |
+
chat_history = []
|
40 |
+
current_chat_history = []
|
41 |
+
|
42 |
+
def data_ingestion_from_directory():
|
43 |
+
# Clear previous data by removing the persist directory
|
44 |
+
if os.path.exists(PERSIST_DIR):
|
45 |
+
shutil.rmtree(PERSIST_DIR) # Remove the persist directory and all its contents
|
46 |
|
47 |
+
# Recreate the persist directory after removal
|
48 |
+
os.makedirs(PERSIST_DIR, exist_ok=True)
|
|
|
49 |
|
50 |
+
# Load new documents from the directory
|
51 |
+
new_documents = SimpleDirectoryReader(PDF_DIRECTORY).load_data()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
+
# Create a new index with the new documents
|
54 |
+
index = VectorStoreIndex.from_documents(new_documents)
|
55 |
|
56 |
+
# Persist the new index
|
57 |
+
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
58 |
+
|
59 |
+
def handle_query(query):
|
60 |
+
chat_text_qa_msgs = [
|
61 |
+
(
|
62 |
+
"user",
|
63 |
+
"""
|
64 |
+
You are the Taj Hotel chatbot and your name is Taj Hotel Helper. Your goal is to provide accurate, professional, and helpful answers to user queries based on the given Taj hotel's data. Always ensure your responses are clear and concise. Give response within 10-15 words only. You need to give an answer in the same language used by the user.
|
65 |
+
{context_str}
|
66 |
+
Question:
|
67 |
+
{query_str}
|
68 |
+
"""
|
69 |
+
)
|
70 |
+
]
|
71 |
+
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
72 |
|
73 |
+
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
74 |
+
index = load_index_from_storage(storage_context)
|
75 |
+
context_str = ""
|
76 |
+
for past_query, response in reversed(current_chat_history):
|
77 |
+
if past_query.strip():
|
78 |
+
context_str += f"User asked: '{past_query}'\nBot answered: '{response}'\n"
|
79 |
+
|
80 |
+
query_engine = index.as_query_engine(text_qa_template=text_qa_template, context_str=context_str)
|
81 |
+
print(query)
|
82 |
+
answer = query_engine.query(query)
|
83 |
+
|
84 |
+
if hasattr(answer, 'response'):
|
85 |
+
response = answer.response
|
86 |
+
elif isinstance(answer, dict) and 'response' in answer:
|
87 |
+
response = answer['response']
|
88 |
+
else:
|
89 |
+
response = "Sorry, I couldn't find an answer."
|
90 |
+
current_chat_history.append((query, response))
|
91 |
+
return response
|
92 |
+
|
93 |
+
app = Flask(__name__)
|
94 |
+
|
95 |
+
# Data ingestion
|
96 |
+
data_ingestion_from_directory()
|
97 |
+
|
98 |
+
# Generate Response
|
99 |
+
def generate_response(query):
|
100 |
+
try:
|
101 |
+
# Call the handle_query function to get the response
|
102 |
+
bot_response = handle_query(query)
|
103 |
+
return bot_response
|
104 |
+
except Exception as e:
|
105 |
+
return f"Error fetching the response: {str(e)}"
|
106 |
+
|
107 |
+
# Route for the homepage
|
108 |
+
@app.route('/')
|
109 |
+
def index():
|
110 |
+
return render_template('index.html')
|
111 |
+
|
112 |
+
# Route to handle chatbot messages
|
113 |
+
@app.route('/chat', methods=['POST'])
|
114 |
+
def chat():
|
115 |
+
try:
|
116 |
+
user_message = request.json.get("message")
|
117 |
+
if not user_message:
|
118 |
+
return jsonify({"response": "Please say something!"})
|
119 |
+
|
120 |
+
bot_response = generate_response(user_message)
|
121 |
+
return jsonify({"response": bot_response})
|
122 |
+
except Exception as e:
|
123 |
+
return jsonify({"response": f"An error occurred: {str(e)}"})
|
124 |
+
|
125 |
+
if __name__ == '__main__':
|
126 |
+
app.run(debug=True)
|