Gopikanth123 commited on
Commit
81ab56f
·
verified ·
1 Parent(s): 7db5311

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +87 -5
main.py CHANGED
@@ -1,5 +1,78 @@
1
  from flask import Flask, render_template, request, jsonify
2
  from gradio_client import Client
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  app = Flask(__name__)
5
 
@@ -10,16 +83,25 @@ except Exception as e:
10
  print(f"Error initializing Gradio client: {str(e)}")
11
  client = None
12
 
13
- # Function to fetch the response from Gradio model
 
 
 
 
 
 
 
 
 
14
  def generate_response(query):
15
- if client is None:
16
- return "Model is unavailable at the moment. Please try again later."
17
  try:
18
- result = client.predict(query=query, api_name="/predict")
19
- return result
 
20
  except Exception as e:
21
  return f"Error fetching the response: {str(e)}"
22
 
 
23
  # Route for the homepage
24
  @app.route('/')
25
  def index():
 
1
  from flask import Flask, render_template, request, jsonify
2
  from gradio_client import Client
3
+ from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate, Settings
4
+ from llama_index.llms.huggingface import HuggingFaceInferenceAPI
5
+ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
6
+ from huggingface_hub import InferenceClient
7
+
8
+ repo_id = "meta-llama/Meta-Llama-3-8B-Instruct"
9
+ llm_client = InferenceClient(
10
+ model=repo_id,
11
+ token=os.getenv("HF_TOKEN"),
12
+ )
13
+
14
+ os.environ["HF_TOKEN"] = os.getenv("HF_TOKEN")
15
+ # Configure Llama index settings
16
+ Settings.llm = HuggingFaceInferenceAPI(
17
+ model_name="meta-llama/Meta-Llama-3-8B-Instruct",
18
+ tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
19
+ context_window=3000,
20
+ token=os.getenv("HF_TOKEN"),
21
+ max_new_tokens=512,
22
+ generate_kwargs={"temperature": 0.1},
23
+ )
24
+ Settings.embed_model = HuggingFaceEmbedding(
25
+ model_name="BAAI/bge-small-en-v1.5"
26
+ )
27
+
28
+ PERSIST_DIR = "db"
29
+ PDF_DIRECTORY = 'data'
30
+
31
+ # Ensure directories exist
32
+ os.makedirs(PDF_DIRECTORY, exist_ok=True)
33
+ os.makedirs(PERSIST_DIR, exist_ok=True)
34
+ chat_history = []
35
+ current_chat_history = []
36
+
37
+ def data_ingestion_from_directory():
38
+ documents = SimpleDirectoryReader(PDF_DIRECTORY).load_data()
39
+ storage_context = StorageContext.from_defaults()
40
+ index = VectorStoreIndex.from_documents(documents)
41
+ index.storage_context.persist(persist_dir=PERSIST_DIR)
42
+
43
+ def handle_query(query):
44
+ chat_text_qa_msgs = [
45
+ (
46
+ "user",
47
+ """
48
+ You are the Hotel voice chatbot and your name is hotel helper. Your goal is to provide accurate, professional, and helpful answers to user queries based on the 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.
49
+ {context_str}
50
+ Question:
51
+ {query_str}
52
+ """
53
+ )
54
+ ]
55
+ text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
56
+
57
+ storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
58
+ index = load_index_from_storage(storage_context)
59
+ context_str = ""
60
+ for past_query, response in reversed(current_chat_history):
61
+ if past_query.strip():
62
+ context_str += f"User asked: '{past_query}'\nBot answered: '{response}'\n"
63
+
64
+ query_engine = index.as_query_engine(text_qa_template=text_qa_template, context_str=context_str)
65
+ print(query)
66
+ answer = query_engine.query(query)
67
+
68
+ if hasattr(answer, 'response'):
69
+ response = answer.response
70
+ elif isinstance(answer, dict) and 'response' in answer:
71
+ response = answer['response']
72
+ else:
73
+ response = "Sorry, I couldn't find an answer."
74
+ current_chat_history.append((query, response))
75
+ return response
76
 
77
  app = Flask(__name__)
78
 
 
83
  print(f"Error initializing Gradio client: {str(e)}")
84
  client = None
85
 
86
+ # # Function to fetch the response from Gradio model
87
+ # def generate_response(query):
88
+ # if client is None:
89
+ # return "Model is unavailable at the moment. Please try again later."
90
+ # try:
91
+ # result = client.predict(query=query, api_name="/predict")
92
+ # return result
93
+ # except Exception as e:
94
+ # return f"Error fetching the response: {str(e)}"
95
+ # Generate Response
96
  def generate_response(query):
 
 
97
  try:
98
+ # Call the handle_query function to get the response
99
+ bot_response = handle_query(query)
100
+ return bot_response
101
  except Exception as e:
102
  return f"Error fetching the response: {str(e)}"
103
 
104
+
105
  # Route for the homepage
106
  @app.route('/')
107
  def index():