Spaces:
Runtime error

deepak0991 commited on
Commit
dfd6ab8
·
verified ·
1 Parent(s): 953df17

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -139
app.py CHANGED
@@ -1,139 +1,139 @@
1
- from dotenv import load_dotenv
2
- import os
3
- import gradio as gr
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
- import firebase_admin
8
- from firebase_admin import db, credentials
9
- import datetime
10
- import uuid
11
- import random
12
-
13
- # Load environment variables
14
- load_dotenv()
15
-
16
- # Authenticate to Firebase
17
- # cred = credentials.Certificate("redfernstech-fd8fe-firebase-adminsdk-g9vcn-0537b4efd6.json")
18
- # firebase_admin.initialize_app(cred, {"databaseURL": "https://redfernstech-fd8fe-default-rtdb.firebaseio.com/"})
19
-
20
- # Configure the Llama index settings
21
- Settings.llm = HuggingFaceInferenceAPI(
22
- model_name="meta-llama/Meta-Llama-3-8B-Instruct",
23
- tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
24
- context_window=3000,
25
- token=os.getenv("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
- # Define the directory for persistent storage and data
34
- PERSIST_DIR = "db"
35
- PDF_DIRECTORY = 'data' # Directory containing PDFs
36
-
37
- # Ensure directories exist
38
- os.makedirs(PDF_DIRECTORY, exist_ok=True)
39
- os.makedirs(PERSIST_DIR, exist_ok=True)
40
-
41
- # Variable to store current chat conversation
42
- current_chat_history = []
43
-
44
- def data_ingestion_from_directory():
45
- # Use SimpleDirectoryReader on the directory containing the PDF files
46
- documents = SimpleDirectoryReader(PDF_DIRECTORY).load_data()
47
- storage_context = StorageContext.from_defaults()
48
- index = VectorStoreIndex.from_documents(documents)
49
- index.storage_context.persist(persist_dir=PERSIST_DIR)
50
-
51
- def handle_query(query):
52
- chat_text_qa_msgs = [
53
- (
54
- "user",
55
- """
56
- You are Clara, the friendly and knowledgeable chatbot of LBRCE (lbrce.ac.in). Your goal is to assist students, parents, and other users by providing accurate, professional, and helpful answers to queries related to the college. Always maintain a warm and engaging tone, starting responses with phrases like "As of my knowledge," "Currently, I understand that," "Based on the latest information," or "At present," to make the interaction feel more personalized.
57
-
58
- When users ask about admission possibilities, such as:
59
- - "My rank is 15273 in EAPCET under EWS category, can I get into CSE department?"
60
- - "What is the closing rank for CSE in EAPCET 2023?"
61
- - "Can I apply for IT if my rank is 45000 under BC-B category?"
62
-
63
- Ensure that all critical details are present in the user's query, specifically:
64
- - **Rank**: The rank obtained in the entrance exam.
65
- - **Exam**: The specific exam (e.g., EAPCET, GATE, ICET).
66
- - **Category**: The reservation or special category (e.g., EWS, BC-A, SC).
67
- - **Desired Department**: The specific department or course they wish to join (e.g., CSE, AI&DS).
68
-
69
- If any of these details are missing, respond with a friendly prompt requesting the missing information. For example:
70
- - "To provide a more accurate answer, could you please specify your reservation category?"
71
- - "It seems like you mentioned your rank but not the desired department. Could you share that as well?"
72
- - "I noticed that your query lacks the exam name. Kindly let me know which exam you are referring to (e.g., EAPCET, ICET)."
73
-
74
- When responding, avoid technical jargon or phrases like "as per the provided document" or "according to the data" and instead make your answers conversational and easy to understand. Be concise but thorough, ensuring that the user leaves with a complete understanding of the information they requested.
75
-
76
- Additionally, Clara should be able to handle general queries such as:
77
- - Details about various undergraduate and postgraduate programs offered.
78
- - Information on special category reservations, including EWS, CAP, NCC, PHO, PHV, PHH, and SG.
79
- - Information about facilities, faculty, placements, and scholarships.
80
- - Details of the application process, important dates, and eligibility criteria.
81
- - Campus life, hostel facilities, and extracurricular opportunities.
82
-
83
- When providing information, ensure that:
84
- - For ranks and admission-related queries, respond with a clear indication of the eligibility or chance of admission based on the provided rank and category.
85
- - For general queries, summarize the information in a user-friendly way without overwhelming the user.
86
- - Clarify any complex details by breaking them into simpler explanations.
87
-
88
- Remember, the user's experience should feel as if they are speaking to a knowledgeable guide who understands their needs and provides clear, direct answers with empathy and professionalism.
89
-
90
- {context_str}
91
- Question:
92
- {query_str}
93
- """
94
- )
95
- ]
96
-
97
- text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
98
-
99
- # Load index from storage
100
- storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
101
- index = load_index_from_storage(storage_context)
102
-
103
- # Use chat history to enhance response
104
- context_str = ""
105
- for past_query, response in reversed(current_chat_history):
106
- if past_query.strip():
107
- context_str += f"User asked: '{past_query}'\nBot answered: '{response}'\n"
108
-
109
- query_engine = index.as_query_engine(text_qa_template=text_qa_template, context_str=context_str)
110
- answer = query_engine.query(query)
111
-
112
- if hasattr(answer, 'response'):
113
- response = answer.response
114
- elif isinstance(answer, dict) and 'response' in answer:
115
- response = answer['response']
116
- else:
117
- response = "Sorry, I couldn't find an answer."
118
-
119
- # Update current chat history
120
- current_chat_history.append((query, response))
121
-
122
- return response
123
-
124
- # Example usage: Process PDF ingestion from directory
125
- print("Processing PDF ingestion from directory:", PDF_DIRECTORY)
126
- data_ingestion_from_directory()
127
-
128
- # Define the Gradio interface function
129
- def chat_interface(message):
130
- response = handle_query(message) # Get the chatbot response
131
- return response
132
-
133
- # Launch Gradio interface
134
- gr.Interface(fn=chat_interface,
135
- inputs="text",
136
- outputs="text",
137
- title="Clara - LBRCE Chatbot",
138
- description="Ask questions related to LBRCE college.") \
139
- .launch()
 
1
+ from dotenv import load_dotenv
2
+ import os
3
+ import gradio as gr
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
+ import firebase_admin
8
+ from firebase_admin import db, credentials
9
+ import datetime
10
+ import uuid
11
+ import random
12
+
13
+ # Load environment variables
14
+ load_dotenv()
15
+
16
+ # Authenticate to Firebase
17
+ # cred = credentials.Certificate("redfernstech-fd8fe-firebase-adminsdk-g9vcn-0537b4efd6.json")
18
+ # firebase_admin.initialize_app(cred, {"databaseURL": "https://redfernstech-fd8fe-default-rtdb.firebaseio.com/"})
19
+
20
+ # Configure the Llama index settings
21
+ Settings.llm = HuggingFaceInferenceAPI(
22
+ model_name="meta-llama/Meta-Llama-3-8B-Instruct",
23
+ tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
24
+ context_window=3000,
25
+ token=os.getenv("HF_TOKEN"),
26
+ max_new_tokens=1024,
27
+ generate_kwargs={"temperature": 0.1},
28
+ )
29
+ Settings.embed_model = HuggingFaceEmbedding(
30
+ model_name="BAAI/bge-small-en-v1.5"
31
+ )
32
+
33
+ # Define the directory for persistent storage and data
34
+ PERSIST_DIR = "db"
35
+ PDF_DIRECTORY = 'data' # Directory containing PDFs
36
+
37
+ # Ensure directories exist
38
+ os.makedirs(PDF_DIRECTORY, exist_ok=True)
39
+ os.makedirs(PERSIST_DIR, exist_ok=True)
40
+
41
+ # Variable to store current chat conversation
42
+ current_chat_history = []
43
+
44
+ def data_ingestion_from_directory():
45
+ # Use SimpleDirectoryReader on the directory containing the PDF files
46
+ documents = SimpleDirectoryReader(PDF_DIRECTORY).load_data()
47
+ storage_context = StorageContext.from_defaults()
48
+ index = VectorStoreIndex.from_documents(documents)
49
+ index.storage_context.persist(persist_dir=PERSIST_DIR)
50
+
51
+ def handle_query(query):
52
+ chat_text_qa_msgs = [
53
+ (
54
+ "user",
55
+ """
56
+ You are Clara, the friendly and knowledgeable chatbot of LBRCE (lbrce.ac.in). Your goal is to assist students, parents, and other users by providing accurate, professional, and helpful answers to queries related to the college. Always maintain a warm and engaging tone, starting responses with phrases like "As of my knowledge," "Currently, I understand that," "Based on the latest information," or "At present," to make the interaction feel more personalized.
57
+
58
+ When users ask about admission possibilities, such as:
59
+ - "My rank is 15273 in EAPCET under EWS category, can I get into CSE department?"
60
+ - "What is the closing rank for CSE in EAPCET 2023?"
61
+ - "Can I apply for IT if my rank is 45000 under BC-B category?"
62
+
63
+ Ensure that all critical details are present in the user's query, specifically:
64
+ - **Rank**: The rank obtained in the entrance exam.
65
+ - **Exam**: The specific exam (e.g., EAPCET, GATE, ICET).
66
+ - **Category**: The reservation or special category (e.g., EWS, BC-A, SC).
67
+ - **Desired Department**: The specific department or course they wish to join (e.g., CSE, AI&DS).
68
+
69
+ If any of these details are missing, respond with a friendly prompt requesting the missing information. For example:
70
+ - "To provide a more accurate answer, could you please specify your reservation category?"
71
+ - "It seems like you mentioned your rank but not the desired department. Could you share that as well?"
72
+ - "I noticed that your query lacks the exam name. Kindly let me know which exam you are referring to (e.g., EAPCET, ICET)."
73
+
74
+ When responding, avoid technical jargon or phrases like "as per the provided document" or "according to the data" and instead make your answers conversational and easy to understand. Be concise but thorough, ensuring that the user leaves with a complete understanding of the information they requested.
75
+
76
+ Additionally, Clara should be able to handle general queries such as:
77
+ - Details about various undergraduate and postgraduate programs offered.
78
+ - Information on special category reservations, including EWS, CAP, NCC, PHO, PHV, PHH, and SG.
79
+ - Information about facilities, faculty, placements, and scholarships.
80
+ - Details of the application process, important dates, and eligibility criteria.
81
+ - Campus life, hostel facilities, and extracurricular opportunities.
82
+
83
+ When providing information, ensure that:
84
+ - For ranks and admission-related queries, respond with a clear indication of the eligibility or chance of admission based on the provided rank and category.
85
+ - For general queries, summarize the information in a user-friendly way without overwhelming the user.
86
+ - Clarify any complex details by breaking them into simpler explanations.
87
+
88
+ Remember, the user's experience should feel as if they are speaking to a knowledgeable guide who understands their needs and provides clear, direct answers with empathy and professionalism.
89
+
90
+ {context_str}
91
+ Question:
92
+ {query_str}
93
+ """
94
+ )
95
+ ]
96
+
97
+ text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
98
+
99
+ # Load index from storage
100
+ storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
101
+ index = load_index_from_storage(storage_context)
102
+
103
+ # Use chat history to enhance response
104
+ context_str = ""
105
+ for past_query, response in reversed(current_chat_history):
106
+ if past_query.strip():
107
+ context_str += f"User asked: '{past_query}'\nBot answered: '{response}'\n"
108
+
109
+ query_engine = index.as_query_engine(text_qa_template=text_qa_template, context_str=context_str)
110
+ answer = query_engine.query(query)
111
+
112
+ if hasattr(answer, 'response'):
113
+ response = answer.response
114
+ elif isinstance(answer, dict) and 'response' in answer:
115
+ response = answer['response']
116
+ else:
117
+ response = "Sorry, I couldn't find an answer."
118
+
119
+ # Update current chat history
120
+ current_chat_history.append((query, response))
121
+
122
+ return response
123
+
124
+ # Example usage: Process PDF ingestion from directory
125
+ print("Processing PDF ingestion from directory:", PDF_DIRECTORY)
126
+ data_ingestion_from_directory()
127
+
128
+ # Define the Gradio interface function
129
+ def chat_interface(message):
130
+ response = handle_query(message) # Get the chatbot response
131
+ return response
132
+
133
+ # Launch Gradio interface
134
+ gr.Interface(fn=chat_interface,
135
+ inputs="text",
136
+ outputs="text",
137
+ title="Clara - LBRCE Chatbot",
138
+ description="Ask questions related to LBRCE college.") \
139
+ .launch()