CosmoAI commited on
Commit
7d8766d
1 Parent(s): d6d8257

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +205 -24
app.py CHANGED
@@ -1,27 +1,208 @@
1
- import google.generativeai as palm
2
- import streamlit as st
3
- import os
4
-
5
- # Set your API key
6
- palm.configure(api_key = os.environ['PALM_KEY'])
7
-
8
- # Select the PaLM 2 model
9
- model = 'models/text-bison-001'
10
-
11
- # Generate text
12
- if prompt := st.chat_input("Ask your query..."):
13
- enprom = f"""Act as bhagwan krishna and Answer the below provided query in context to first Bhagwad Geeta and then vedas, puranas and shastras if required. Use the verses and chapters sentences as references to your answer with suggestions
14
- coming from Bhagwad Geeta or vedas. Your answer to below query should be friendly and represent the characterstics of bhagwan krishna with fun and all knowing almight trait.\nQuery= {prompt}"""
15
- completion = palm.generate_text(model=model, prompt=enprom, temperature=0.5, max_output_tokens=800)
16
-
17
- # response = palm.chat(messages=["Hello."])
18
- # print(response.last) # 'Hello! What can I help you with?'
19
- # response.reply("Can you tell me a joke?")
20
-
21
- # Print the generated text
22
- with st.chat_message("Assistant"):
23
- st.write(prompt)
24
- st.write(completion.result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
 
27
 
 
1
+ import nltk
2
+ from nltk.corpus import stopwords
3
+ from nltk.stem import PorterStemmer
4
+
5
+ # Download necessary resources (comment out if already downloaded)
6
+ nltk.download('punkt')
7
+ nltk.download('stopwords')
8
+
9
+ def preprocess_text(text):
10
+ """
11
+ This function preprocesses the text for training.
12
+
13
+ Args:
14
+ text: String containing the text data.
15
+
16
+ Returns:
17
+ A list of preprocessed tokens.
18
+ """
19
+ # Tokenization
20
+ tokens = nltk.word_tokenize(text.lower()) # Lowercase and tokenize
21
+
22
+ # Stop word removal
23
+ stop_words = set(stopwords.words('english'))
24
+ tokens = [word for word in tokens if word not in stop_words]
25
+
26
+ # Stemming (optional - Experiment with stemming vs lemmatization)
27
+ stemmer = PorterStemmer()
28
+ tokens = [stemmer.stem(word) for word in tokens]
29
+
30
+ return tokens
31
+
32
+ # Read the Bhagavad Gita text file
33
+ with open("Geeta.txt", "r") as f:
34
+ bhagavad_gita_text = f.read()
35
+
36
+ # Preprocess the text
37
+ preprocessed_text = preprocess_text(bhagavad_gita_text)
38
+
39
+ # Install spaCy (if not already installed)
40
+ # pip install spacy
41
+ import spacy
42
+
43
+ # Load a spaCy model for English language processing
44
+ nlp = spacy.load("en_core_web_sm")
45
+
46
+ def extractive_qa(question, text):
47
+ """
48
+ This function attempts to answer a question by extracting relevant phrases from the text.
49
+
50
+ Args:
51
+ question: The user's question.
52
+ text: The text to search for answers (Bhagavad Gita text).
53
+
54
+ Returns:
55
+ A potential answer extracted from the text (or None if not found).
56
+ """
57
+ doc = nlp(text)
58
+ doc_question = nlp(question)
59
+
60
+ # Identify named entities and noun phrases in the question that might be relevant for searching the text
61
+ answer_candidates = []
62
+ for ent in doc_question.ents:
63
+ answer_candidates.append(ent.text)
64
+ for chunk in doc_question.noun_chunks:
65
+ answer_candidates.append(chunk.text)
66
+
67
+ # Search for the answer candidates within the text and return the first match
68
+ for candidate in answer_candidates:
69
+ if candidate in text:
70
+ return candidate
71
+ return None
72
+
73
+ # Use extractive_qa to generate some question-answer pairs from the Bhagavad Gita text
74
+ qa_pairs = []
75
+ for question in ["What is karma?", "Who is Arjuna?"]:
76
+ answer = extractive_qa(question, bhagavad_gita_text)
77
+ if answer:
78
+ qa_pairs.append((question, answer))
79
+
80
+ # You can combine manually curated and extractive QA pairs for a richer dataset.
81
+ # Create a list of question-answer pairs manually (replace with your examples)
82
+ # qa_pairs = [
83
+ # ("What is the central message of the Bhagavad Gita?", "The Bhagavad Gita emphasizes the importance of fulfilling one's duty without attachment to the outcome."),
84
+ # ("What is the role of Krishna in the Bhagavad Gita?", "Krishna acts as Arjuna's charioteer and divine guide, offering him philosophical knowledge and motivation to perform his duty."),
85
+ # # Add more question-answer pairs...
86
+ # ]
87
+ from transformers import BertTokenizer, TFBertForQuestionAnswering
88
+ from transformers import Adam # Optimizer (optional)
89
+ from transformers import SquadLoss # Loss function (optional)
90
+
91
+ # Load pre-trained model and tokenizer
92
+ tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
93
+ model = TFBertForQuestionAnswering.from_pretrained('bert-base-uncased')
94
+
95
+
96
+ # Function to prepare training data for transformers (omitted for brevity)
97
+ def prepare_training_data(qa_pairs, tokenizer):
98
+ """
99
+ This function prepares training data for a question answering model by converting
100
+ question-answer pairs into model inputs (token IDs, attention masks).
101
+
102
+ Args:
103
+ qa_pairs: A list of tuples containing (question, answer) pairs.
104
+ tokenizer: A pre-trained tokenizer (e.g., BertTokenizer).
105
+
106
+ Returns:
107
+ A list of dictionaries containing model inputs for each question-answer pair.
108
+ """
109
+
110
+ encoded_data = []
111
+ for question, answer in qa_pairs:
112
+ # Tokenize question and answer
113
+ question_encoded = tokenizer(question, add_special_tokens=True, return_tensors="pt")
114
+ answer_encoded = tokenizer(answer, add_special_tokens=True, return_tensors="pt")
115
+
116
+ # Create attention masks to identify relevant parts of the sequence
117
+ question_mask = question_encoded["attention_mask"]
118
+ answer_mask = answer_encoded["attention_mask"]
119
+
120
+ # Get start and end token IDs for the answer within the context (Bhagavad Gita text)
121
+ # This step might require adjustments depending on how you represent the context.
122
+ # Here, we assume the context is a single long string.
123
+ context = "your_bhagavad_gita_text_here" # Replace with your preprocessed Bhagavad Gita text
124
+ context_encoded = tokenizer(context, add_special_tokens=True, return_tensors="pt")
125
+ start_positions = answer_encoded.input_ids == tokenizer.convert_tokens_to_ids(tokenizer.sep_token)[0] # Find first SEP token
126
+ end_positions = answer_encoded.input_ids == tokenizer.convert_tokens_to_ids(tokenizer.eos_token)[0] # Find first EOS token
127
+
128
+ # Combine all data into a dictionary for each QA pair
129
+ encoded_data.append({
130
+ "question_input_ids": question_encoded["input_ids"],
131
+ "question_attention_mask": question_mask,
132
+ "answer_start_positions": start_positions,
133
+ "answer_end_positions": end_positions,
134
+ })
135
+
136
+ return encoded_data
137
+
138
+ # Prepare training data
139
+ train_data = prepare_training_data(qa_pairs)
140
+
141
+ # Train the model
142
+ learning_rate = 2e-5
143
+ epochs = 3 # Adjust these values as needed
144
+ model.compile(optimizer=Adam(learning_rate=learning_rate), loss=SquadLoss())
145
+ model.fit(train_data, epochs=epochs)
146
+
147
+ # Save the trained model and tokenizer
148
+ model.save_pretrained("bhagavad_gita_qa_model")
149
+ tokenizer.save_pretrained("bhagavad_gita_qa_model")
150
+
151
+ print("Model and tokenizer saved successfully!")
152
+
153
+ import streamlit as st
154
+ from transformers import pipeline # For loading the QA model
155
+
156
+ qa_pipeline = pipeline("question-answering", model="bhagavad_gita_qa_model")
157
+
158
+ st.title("Bhagavad Gita Question Answering")
159
+ st.subheader("Ask your questions about the Bhagavad Gita here.")
160
+
161
+ user_question = st.text_input("Enter your question:")
162
+
163
+ if user_question:
164
+ # Pass the user question and Bhagavad Gita text to the loaded model
165
+ answer = qa_pipeline(question=user_question, context=bhagavad_gita_text)
166
+ st.write(f"Answer: {answer['answer']}")
167
+ # Optionally, display additional information like confidence score
168
+ # st.write(f"Confidence Score: {answer['score']}")
169
+
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+
182
+ # import google.generativeai as palm
183
+ # import streamlit as st
184
+ # import os
185
+
186
+ # # Set your API key
187
+ # palm.configure(api_key = os.environ['PALM_KEY'])
188
+
189
+ # # Select the PaLM 2 model
190
+ # model = 'models/text-bison-001'
191
+
192
+ # # Generate text
193
+ # if prompt := st.chat_input("Ask your query..."):
194
+ # enprom = f"""Act as bhagwan krishna and Answer the below provided query in context to first Bhagwad Geeta and then vedas, puranas and shastras if required. Use the verses and chapters sentences as references to your answer with suggestions
195
+ # coming from Bhagwad Geeta or vedas. Your answer to below query should be friendly and represent the characterstics of bhagwan krishna with fun and all knowing almight trait.\nQuery= {prompt}"""
196
+ # completion = palm.generate_text(model=model, prompt=enprom, temperature=0.5, max_output_tokens=800)
197
+
198
+ # # response = palm.chat(messages=["Hello."])
199
+ # # print(response.last) # 'Hello! What can I help you with?'
200
+ # # response.reply("Can you tell me a joke?")
201
+
202
+ # # Print the generated text
203
+ # with st.chat_message("Assistant"):
204
+ # st.write(prompt)
205
+ # st.write(completion.result)
206
 
207
 
208