RAMYASRI-39 commited on
Commit
bd218cf
·
verified ·
1 Parent(s): 9dd8c2a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +446 -173
app.py CHANGED
@@ -1,41 +1,54 @@
1
- import requests
2
  import gradio as gr
3
- from ragatouille import RAGPretrainedModel
 
 
4
  import logging
5
- from pathlib import Path
6
- from time import perf_counter
7
  from sentence_transformers import CrossEncoder
8
- from huggingface_hub import InferenceClient
9
- from jinja2 import Environment, FileSystemLoader
10
- import numpy as np
11
- from os import getenv
12
- from backend.query_llm import generate_hf, generate_qwen
13
  from backend.semantic_search import table, retriever
14
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
15
 
 
 
 
 
 
 
 
 
16
 
17
- # Bhashini API translation function
18
- api_key = getenv('API_KEY')
19
- user_id = getenv('USER_ID')
20
 
21
  def bhashini_translate(text: str, from_code: str = "en", to_code: str = "hi") -> dict:
22
  """Translates text from source language to target language using the Bhashini API."""
23
-
24
  if not text.strip():
25
  print('Input text is empty. Please provide valid text for translation.')
26
- return {"status_code": 400, "message": "Input text is empty", "translated_content": None, "speech_content": None}
27
  else:
28
- print('Input text - ',text)
29
- print(f'Starting translation process from {from_code} to {to_code}...')
30
  print(f'Starting translation process from {from_code} to {to_code}...')
31
  gr.Warning(f'Translating to {to_code}...')
32
 
33
  url = 'https://meity-auth.ulcacontrib.org/ulca/apis/v0/model/getModelsPipeline'
34
  headers = {
35
  "Content-Type": "application/json",
36
- "userID": user_id,
37
- "ulcaApiKey": api_key
38
  }
 
 
 
 
 
39
  payload = {
40
  "pipelineTasks": [{"taskType": "translation", "config": {"language": {"sourceLanguage": from_code, "targetLanguage": to_code}}}],
41
  "pipelineRequestConfig": {"pipelineId": "64392f96daac500b55c543cd"}
@@ -45,11 +58,16 @@ def bhashini_translate(text: str, from_code: str = "en", to_code: str = "hi") ->
45
  response = requests.post(url, json=payload, headers=headers)
46
 
47
  if response.status_code != 200:
48
- print(f'Error in initial request: {response.status_code}')
49
  return {"status_code": response.status_code, "message": "Error in translation request", "translated_content": None}
50
 
51
  print('Initial request successful, processing response...')
52
  response_data = response.json()
 
 
 
 
 
53
  service_id = response_data["pipelineResponseConfig"][0]["config"][0]["serviceId"]
54
  callback_url = response_data["pipelineInferenceAPIEndPoint"]["callbackUrl"]
55
 
@@ -68,7 +86,7 @@ def bhashini_translate(text: str, from_code: str = "en", to_code: str = "hi") ->
68
  compute_response = requests.post(callback_url, json=compute_payload, headers=headers2)
69
 
70
  if compute_response.status_code != 200:
71
- print(f'Error in translation request: {compute_response.status_code}')
72
  return {"status_code": compute_response.status_code, "message": "Error in translation", "translated_content": None}
73
 
74
  print('Translation request successful, processing translation...')
@@ -78,157 +96,123 @@ def bhashini_translate(text: str, from_code: str = "en", to_code: str = "hi") ->
78
  print(f'Translation successful. Translated content: "{translated_content}"')
79
  return {"status_code": 200, "message": "Translation successful", "translated_content": translated_content}
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- # Existing chatbot functions
83
- VECTOR_COLUMN_NAME = "vector"
84
- TEXT_COLUMN_NAME = "text"
85
- HF_TOKEN = getenv("HUGGING_FACE_HUB_TOKEN")
86
  proj_dir = Path(__file__).parent
87
-
88
- logging.basicConfig(level=logging.INFO)
89
- logger = logging.getLogger(__name__)
90
- client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1", token=HF_TOKEN)
91
  env = Environment(loader=FileSystemLoader(proj_dir / 'templates'))
 
 
92
 
93
- template = env.get_template('template.j2')
94
- template_html = env.get_template('template_html.j2')
95
-
96
- # def add_text(history, text):
97
- # history = [] if history is None else history
98
- # history = history + [(text, None)]
99
- # return history, gr.Textbox(value="", interactive=False)
100
-
101
- def bot(history, cross_encoder):
102
-
103
  top_rerank = 25
104
  top_k_rank = 20
105
- query = history[-1][0] if history else ''
106
- print('\nQuery: ',query )
107
- print('\nHistory:',history)
108
- if not query:
109
- gr.Warning("Please submit a non-empty string as a prompt")
110
- raise ValueError("Empty string was submitted")
111
-
112
- logger.warning('Retrieving documents...')
113
-
114
- if cross_encoder == '(HIGH ACCURATE) ColBERT':
115
- gr.Warning('Retrieving using ColBERT.. First time query will take a minute for model to load..pls wait')
116
- RAG = RAGPretrainedModel.from_pretrained("colbert-ir/colbertv2.0")
117
- RAG_db = RAG.from_index('.ragatouille/colbert/indexes/cbseclass10index')
118
- documents_full = RAG_db.search(query, k=top_k_rank)
119
-
120
- documents = [item['content'] for item in documents_full]
121
- prompt = template.render(documents=documents, query=query)
122
- prompt_html = template_html.render(documents=documents, query=query)
123
 
124
- generate_fn = generate_hf
125
-
126
- history[-1][1] = ""
127
- for character in generate_fn(prompt, history[:-1]):
128
- history[-1][1] = character
129
- yield history, prompt_html
130
- else:
131
- document_start = perf_counter()
132
 
 
 
 
 
133
  query_vec = retriever.encode(query)
134
- doc1 = table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank)
135
-
136
- documents = table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_rerank).to_list()
137
- documents = [doc[TEXT_COLUMN_NAME] for doc in documents]
138
-
139
- query_doc_pair = [[query, doc] for doc in documents]
140
- if cross_encoder == '(FAST) MiniLM-L6v2':
141
- cross_encoder1 = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
142
- elif cross_encoder == '(ACCURATE) BGE reranker':
143
- cross_encoder1 = CrossEncoder('BAAI/bge-reranker-base')
144
 
145
- cross_scores = cross_encoder1.predict(query_doc_pair)
 
 
 
146
  sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
147
-
148
  documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
149
-
150
- document_time = perf_counter() - document_start
151
-
152
- prompt = template.render(documents=documents, query=query)
153
- prompt_html = template_html.render(documents=documents, query=query)
154
-
155
- #generate_fn = generate_hf
156
- generate_fn=generate_qwen
157
- # Create a new history entry instead of modifying the tuple directly
158
- new_history = history[:-1] + [ (prompt, "") ] # query replaced prompt
159
- output=''
160
- # for character in generate_fn(prompt, history[:-1]):
161
- # #new_history[-1] = (query, character)
162
- # output+=character
163
- output=generate_fn(prompt, history[:-1])
164
 
165
- print('Output:',output)
166
- new_history[-1] = (prompt, output) #query replaced with prompt
167
- print('New History',new_history)
168
- #print('prompt html',prompt_html)# Update the last tuple with new text
169
 
170
- history_list = list(history[-1])
171
- history_list[1] = output # Assuming `character` is what you want to assign
172
- # Update the history with the modified list converted back to a tuple
173
- history[-1] = tuple(history_list)
174
-
175
- #history[-1][1] = character
176
- # yield new_history, prompt_html
177
- yield history, prompt_html
178
- # new_history,prompt_html
179
- # history[-1][1] = ""
180
- # for character in generate_fn(prompt, history[:-1]):
181
- # history[-1][1] = character
182
- # yield history, prompt_html
 
 
 
 
 
 
 
183
 
184
- #def translate_text(response_text, selected_language):
 
 
 
185
 
186
- def translate_text(selected_language,history):
 
187
 
 
 
 
 
 
 
 
 
 
 
188
  iso_language_codes = {
189
- "Hindi": "hi",
190
- "Gom": "gom",
191
- "Kannada": "kn",
192
- "Dogri": "doi",
193
- "Bodo": "brx",
194
- "Urdu": "ur",
195
- "Tamil": "ta",
196
- "Kashmiri": "ks",
197
- "Assamese": "as",
198
- "Bengali": "bn",
199
- "Marathi": "mr",
200
- "Sindhi": "sd",
201
- "Maithili": "mai",
202
- "Punjabi": "pa",
203
- "Malayalam": "ml",
204
- "Manipuri": "mni",
205
- "Telugu": "te",
206
- "Sanskrit": "sa",
207
- "Nepali": "ne",
208
- "Santali": "sat",
209
- "Gujarati": "gu",
210
- "Odia": "or"
211
  }
212
 
213
  to_code = iso_language_codes[selected_language]
214
- response_text = history[-1][1] if history else ''
215
- print('response_text for translation',response_text)
216
  translation = bhashini_translate(response_text, to_code=to_code)
217
- return translation['translated_content']
218
-
219
 
220
- # Gradio interface
221
- with gr.Blocks(theme='gradio/soft') as CHATBOT:
222
- history_state = gr.State([])
223
  with gr.Row():
224
  with gr.Column(scale=10):
225
- gr.HTML(value="""<div style="color: #FF4500;"><h1>Welcome! I am your friend!</h1>Ask me !I will help you<h1><span style="color: #008000">I AM A CHATBOT FOR 10 SOCIAL WITH TRANSLATION IN 22 LANGUAGES</span></h1></div>""")
226
  gr.HTML(value=f"""<p style="font-family: sans-serif; font-size: 16px;">A free chat bot developed by K.M.RAMYASRI,TGT,GHS.SUTHUKENY using Open source LLMs for 10 std students</p>""")
227
  gr.HTML(value=f"""<p style="font-family: Arial, sans-serif; font-size: 14px;"> Suggestions may be sent to <a href="mailto:[email protected]" style="color: #00008B; font-style: italic;">[email protected]</a>.</p>""")
228
-
229
  with gr.Column(scale=3):
230
- gr.Image(value='logo.png', height=200, width=200)
 
 
 
231
 
 
232
  chatbot = gr.Chatbot(
233
  [],
234
  elem_id="chatbot",
@@ -240,56 +224,345 @@ with gr.Blocks(theme='gradio/soft') as CHATBOT:
240
  )
241
 
242
  with gr.Row():
243
- txt = gr.Textbox(
244
  scale=3,
245
  show_label=False,
246
  placeholder="Enter text and press enter",
247
  container=False,
248
  )
249
- txt_btn = gr.Button(value="Submit text", scale=1)
250
-
251
- cross_encoder = gr.Radio(choices=['(FAST) MiniLM-L6v2', '(ACCURATE) BGE reranker', '(HIGH ACCURATE) ColBERT'], value='(ACCURATE) BGE reranker', label="Embeddings", info="Only First query to Colbert may take little time)")
 
 
 
 
 
 
252
  language_dropdown = gr.Dropdown(
253
  choices=[
254
  "Hindi", "Gom", "Kannada", "Dogri", "Bodo", "Urdu", "Tamil", "Kashmiri", "Assamese", "Bengali", "Marathi",
255
  "Sindhi", "Maithili", "Punjabi", "Malayalam", "Manipuri", "Telugu", "Sanskrit", "Nepali", "Santali",
256
  "Gujarati", "Odia"
257
  ],
258
- value="Hindi", # default to Hindi
259
  label="Select Language for Translation"
260
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
 
262
- prompt_html = gr.HTML()
 
 
 
 
 
 
 
 
 
263
 
264
- translated_textbox = gr.Textbox(label="Translated Response")
265
- def update_history_and_translate(txt, cross_encoder, history_state, language_dropdown):
266
- print('History state',history_state)
267
- history = history_state
268
- history.append((txt, ""))
269
- #history_state.value=(history)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
- # Call bot function
272
- # bot_output = list(bot(history, cross_encoder))
273
- bot_output = next(bot(history, cross_encoder))
274
- print('bot_output',bot_output)
275
- #history, prompt_html = bot_output[-1]
276
- history, prompt_html = bot_output
277
- print('History',history)
278
- # Update the history state
279
- history_state[:] = history
280
 
281
- # Translate text
282
- translated_text = translate_text(language_dropdown, history)
283
- return history, prompt_html, translated_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
 
285
- txt_msg = txt_btn.click(update_history_and_translate, [txt, cross_encoder, history_state, language_dropdown], [chatbot, prompt_html, translated_textbox])
286
- txt_msg = txt.submit(update_history_and_translate, [txt, cross_encoder, history_state, language_dropdown], [chatbot, prompt_html, translated_textbox])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
 
288
- examples = ['WHAT IS POWER SHARING?','WHAT IS THE REASON FOR RISE OF NATIONALISM IN INDIA?']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
 
290
- gr.Examples(examples, txt)
 
291
 
 
 
292
 
293
- # Launch the Gradio application
294
- CHATBOT.launch(share=True,debug=True)
 
 
 
 
 
 
 
 
 
 
295
 
 
 
 
 
1
  import gradio as gr
2
+ from phi.agent import Agent
3
+ from phi.model.groq import Groq
4
+ import os
5
  import logging
 
 
6
  from sentence_transformers import CrossEncoder
 
 
 
 
 
7
  from backend.semantic_search import table, retriever
8
+ import numpy as np
9
+ from time import perf_counter
10
+ import requests
11
+ from jinja2 import Environment, FileSystemLoader
12
+ from pathlib import Path
13
+
14
+ # Set up logging
15
+ logging.basicConfig(level=logging.INFO)
16
+ logger = logging.getLogger(__name__)
17
 
18
+ # API Key setup
19
+ api_key = os.getenv("GROQ_API_KEY")
20
+ if not api_key:
21
+ gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
22
+ logger.error("GROQ_API_KEY not found.")
23
+ api_key = "" # Fallback to empty string, but this will fail without a key
24
+ else:
25
+ os.environ["GROQ_API_KEY"] = api_key
26
 
27
+ # Bhashini API setup
28
+ bhashini_api_key = os.getenv("API_KEY", "").strip()
29
+ bhashini_user_id = os.getenv("USER_ID", "").strip()
30
 
31
  def bhashini_translate(text: str, from_code: str = "en", to_code: str = "hi") -> dict:
32
  """Translates text from source language to target language using the Bhashini API."""
 
33
  if not text.strip():
34
  print('Input text is empty. Please provide valid text for translation.')
35
+ return {"status_code": 400, "message": "Input text is empty", "translated_content": None}
36
  else:
37
+ print('Input text - ', text)
 
38
  print(f'Starting translation process from {from_code} to {to_code}...')
39
  gr.Warning(f'Translating to {to_code}...')
40
 
41
  url = 'https://meity-auth.ulcacontrib.org/ulca/apis/v0/model/getModelsPipeline'
42
  headers = {
43
  "Content-Type": "application/json",
44
+ "userID": bhashini_user_id,
45
+ "ulcaApiKey": bhashini_api_key
46
  }
47
+ for key, value in headers.items():
48
+ if not isinstance(value, str) or '\n' in value or '\r' in value:
49
+ print(f"Invalid header value for {key}: {value}")
50
+ return {"status_code": 400, "message": f"Invalid header value for {key}", "translated_content": None}
51
+
52
  payload = {
53
  "pipelineTasks": [{"taskType": "translation", "config": {"language": {"sourceLanguage": from_code, "targetLanguage": to_code}}}],
54
  "pipelineRequestConfig": {"pipelineId": "64392f96daac500b55c543cd"}
 
58
  response = requests.post(url, json=payload, headers=headers)
59
 
60
  if response.status_code != 200:
61
+ print(f'Error in initial request: {response.status_code}, Response: {response.text}')
62
  return {"status_code": response.status_code, "message": "Error in translation request", "translated_content": None}
63
 
64
  print('Initial request successful, processing response...')
65
  response_data = response.json()
66
+ print('Full response data:', response_data)
67
+ if "pipelineInferenceAPIEndPoint" not in response_data or "callbackUrl" not in response_data["pipelineInferenceAPIEndPoint"]:
68
+ print('Unexpected response structure:', response_data)
69
+ return {"status_code": 400, "message": "Unexpected API response structure", "translated_content": None}
70
+
71
  service_id = response_data["pipelineResponseConfig"][0]["config"][0]["serviceId"]
72
  callback_url = response_data["pipelineInferenceAPIEndPoint"]["callbackUrl"]
73
 
 
86
  compute_response = requests.post(callback_url, json=compute_payload, headers=headers2)
87
 
88
  if compute_response.status_code != 200:
89
+ print(f'Error in translation request: {compute_response.status_code}, Response: {compute_response.text}')
90
  return {"status_code": compute_response.status_code, "message": "Error in translation", "translated_content": None}
91
 
92
  print('Translation request successful, processing translation...')
 
96
  print(f'Translation successful. Translated content: "{translated_content}"')
97
  return {"status_code": 200, "message": "Translation successful", "translated_content": translated_content}
98
 
99
+ # Initialize PhiData Agent
100
+ agent = Agent(
101
+ name="Science Education Assistant",
102
+ role="You are a helpful science tutor for 10th-grade students",
103
+ instructions=[
104
+ "You are an expert science teacher specializing in 10th-grade curriculum.",
105
+ "Provide clear, accurate, and age-appropriate explanations.",
106
+ "Use simple language and examples that students can understand.",
107
+ "Focus on concepts from physics, chemistry, and biology.",
108
+ "Structure responses with headings and bullet points when helpful.",
109
+ "Encourage learning and curiosity."
110
+ ],
111
+ model=Groq(id="llama3-70b-8192", api_key=api_key),
112
+ markdown=True
113
+ )
114
 
115
+ # Set up Jinja2 environment
 
 
 
116
  proj_dir = Path(__file__).parent
 
 
 
 
117
  env = Environment(loader=FileSystemLoader(proj_dir / 'templates'))
118
+ template = env.get_template('template.j2') # For document context
119
+ template_html = env.get_template('template_html.j2') # For HTML output
120
 
121
+ # Response Generation Function
122
+ def retrieve_and_generate_response(query, cross_encoder_choice, history=None):
123
+ """Generate response using semantic search and LLM"""
 
 
 
 
 
 
 
124
  top_rerank = 25
125
  top_k_rank = 20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
+ if not query.strip():
128
+ return "Please provide a valid question.", []
 
 
 
 
 
 
129
 
130
+ try:
131
+ start_time = perf_counter()
132
+
133
+ # Encode query and search documents
134
  query_vec = retriever.encode(query)
135
+ documents = table.search(query_vec, vector_column_name="vector").limit(top_rerank).to_list()
136
+ documents = [doc["text"] for doc in documents]
 
 
 
 
 
 
 
 
137
 
138
+ # Re-rank documents using cross-encoder
139
+ cross_encoder_model = CrossEncoder('BAAI/bge-reranker-base') if cross_encoder_choice == '(ACCURATE) BGE reranker' else CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
140
+ query_doc_pair = [[query, doc] for doc in documents]
141
+ cross_scores = cross_encoder_model.predict(query_doc_pair)
142
  sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
 
143
  documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
+ # Create context from top documents
146
+ context = "\n\n".join(documents[:10]) if documents else ""
147
+ context = f"Context information from educational materials:\n{context}\n\n"
 
148
 
149
+ # Add conversation history for context
150
+ history_context = ""
151
+ if history and len(history) > 0:
152
+ for user_msg, bot_msg in history[-2:]: # Last 2 exchanges
153
+ if user_msg and bot_msg:
154
+ history_context += f"Previous Q: {user_msg}\nPrevious A: {bot_msg}\n"
155
+
156
+ # Create full prompt
157
+ full_prompt = f"{history_context}{context}Question: {query}\n\nPlease answer the question using the context provided above. If the context doesn't contain relevant information, use your general knowledge about 10th-grade science topics."
158
+
159
+ # Generate response
160
+ response = agent.run(full_prompt)
161
+ response_text = response.content if hasattr(response, 'content') else str(response)
162
+
163
+ logger.info(f"Response generation took {perf_counter() - start_time:.2f} seconds")
164
+ return response_text, documents # Return documents for template
165
+
166
+ except Exception as e:
167
+ logger.error(f"Error in response generation: {e}")
168
+ return f"Error generating response: {str(e)}", []
169
 
170
+ def simple_chat_function(message, history, cross_encoder_choice):
171
+ """Chat function with semantic search and retriever integration"""
172
+ if not message.strip():
173
+ return "", history, ""
174
 
175
+ # Generate response and get documents
176
+ response, documents = retrieve_and_generate_response(message, cross_encoder_choice, history)
177
 
178
+ # Add to history
179
+ history.append([message, response])
180
+
181
+ # Render template with documents and query
182
+ prompt_html = template_html.render(documents=documents, query=message)
183
+
184
+ return "", history, prompt_html
185
+
186
+ def translate_text(selected_language, history):
187
+ """Translate the last response in history to the selected language."""
188
  iso_language_codes = {
189
+ "Hindi": "hi", "Gom": "gom", "Kannada": "kn", "Dogri": "doi", "Bodo": "brx", "Urdu": "ur",
190
+ "Tamil": "ta", "Kashmiri": "ks", "Assamese": "as", "Bengali": "bn", "Marathi": "mr",
191
+ "Sindhi": "sd", "Maithili": "mai", "Punjabi": "pa", "Malayalam": "ml", "Manipuri": "mni",
192
+ "Telugu": "te", "Sanskrit": "sa", "Nepali": "ne", "Santali": "sat", "Gujarati": "gu", "Odia": "or"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  }
194
 
195
  to_code = iso_language_codes[selected_language]
196
+ response_text = history[-1][1] if history and history[-1][1] else ''
197
+ print('response_text for translation', response_text)
198
  translation = bhashini_translate(response_text, to_code=to_code)
199
+ return translation.get('translated_content', 'Translation failed.')
 
200
 
201
+ # Gradio Interface with layout template
202
+ with gr.Blocks(title="Science Chatbot", theme='gradio/soft') as demo:
203
+ # Header section
204
  with gr.Row():
205
  with gr.Column(scale=10):
206
+ gr.HTML(value="""<div style="color: #FF4500;"><h1>Welcome! I am your friend!</h1>Ask me !I will help you<h1><span style="color: #008000">I AM A CHATBOT FOR 10TH SCIENCE WITH TRANSLATION IN 22 LANGUAGES</span></h1></div>""")
207
  gr.HTML(value=f"""<p style="font-family: sans-serif; font-size: 16px;">A free chat bot developed by K.M.RAMYASRI,TGT,GHS.SUTHUKENY using Open source LLMs for 10 std students</p>""")
208
  gr.HTML(value=f"""<p style="font-family: Arial, sans-serif; font-size: 14px;"> Suggestions may be sent to <a href="mailto:[email protected]" style="color: #00008B; font-style: italic;">[email protected]</a>.</p>""")
 
209
  with gr.Column(scale=3):
210
+ try:
211
+ gr.Image(value='logo.png', height=200, width=200)
212
+ except:
213
+ gr.HTML("<div style='height: 200px; width: 200px; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center;'>Logo</div>")
214
 
215
+ # Chat and input components
216
  chatbot = gr.Chatbot(
217
  [],
218
  elem_id="chatbot",
 
224
  )
225
 
226
  with gr.Row():
227
+ msg = gr.Textbox(
228
  scale=3,
229
  show_label=False,
230
  placeholder="Enter text and press enter",
231
  container=False,
232
  )
233
+ submit_btn = gr.Button(value="Submit text", scale=1, variant="primary")
234
+
235
+ # Additional controls
236
+ cross_encoder = gr.Radio(
237
+ choices=['(FAST) MiniLM-L6v2', '(ACCURATE) BGE reranker'],
238
+ value='(ACCURATE) BGE reranker',
239
+ label="Embeddings Model",
240
+ info="Select the model for document ranking"
241
+ )
242
  language_dropdown = gr.Dropdown(
243
  choices=[
244
  "Hindi", "Gom", "Kannada", "Dogri", "Bodo", "Urdu", "Tamil", "Kashmiri", "Assamese", "Bengali", "Marathi",
245
  "Sindhi", "Maithili", "Punjabi", "Malayalam", "Manipuri", "Telugu", "Sanskrit", "Nepali", "Santali",
246
  "Gujarati", "Odia"
247
  ],
248
+ value="Hindi",
249
  label="Select Language for Translation"
250
  )
251
+ translated_textbox = gr.Textbox(label="Translated Response")
252
+ prompt_html = gr.HTML() # Add HTML component for the template
253
+
254
+ # Event handlers
255
+ def update_chat_and_translate(message, history, cross_encoder_choice, selected_language):
256
+ if not message.strip():
257
+ return "", history, "", ""
258
+
259
+ # Generate response and get documents
260
+ response, documents = retrieve_and_generate_response(message, cross_encoder_choice, history)
261
+ history.append([message, response])
262
+
263
+ # Translate response
264
+ translated_text = translate_text(selected_language, history)
265
+
266
+ # Render template with documents and query
267
+ prompt_html_content = template_html.render(documents=documents, query=message)
268
+
269
+ return "", history, translated_text, prompt_html_content
270
+
271
+ msg.submit(update_chat_and_translate, [msg, chatbot, cross_encoder, language_dropdown], [msg, chatbot, translated_textbox, prompt_html])
272
+ submit_btn.click(update_chat_and_translate, [msg, chatbot, cross_encoder, language_dropdown], [msg, chatbot, translated_textbox, prompt_html])
273
+
274
+ clear = gr.Button("Clear Conversation")
275
+ clear.click(lambda: ([], "", "", ""), outputs=[chatbot, msg, translated_textbox, prompt_html])
276
+
277
+ # Example questions
278
+ gr.Examples(
279
+ examples=[
280
+ 'What is the difference between metals and non-metals?',
281
+ 'What is an ionic bond?',
282
+ 'Explain asexual reproduction',
283
+ 'What is photosynthesis?',
284
+ 'Explain Newton\'s laws of motion'
285
+ ],
286
+ inputs=msg,
287
+ label="Try these example questions:"
288
+ )
289
+
290
+ if __name__ == "__main__":
291
+ demo.launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
292
+ # from phi.agent import Agent
293
+ # from phi.model.groq import Groq
294
+ # import os
295
+ # import logging
296
+ # from sentence_transformers import CrossEncoder
297
+ # from backend.semantic_search import table, retriever
298
+ # import numpy as np
299
+ # from time import perf_counter
300
+ # import requests
301
+ # from jinja2 import Environment, FileSystemLoader
302
+
303
+ # # Set up logging
304
+ # logging.basicConfig(level=logging.INFO)
305
+ # logger = logging.getLogger(__name__)
306
+
307
+ # # API Key setup
308
+ # api_key = os.getenv("GROQ_API_KEY")
309
+ # if not api_key:
310
+ # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
311
+ # logger.error("GROQ_API_KEY not found.")
312
+ # api_key = "" # Fallback to empty string, but this will fail without a key
313
+ # else:
314
+ # os.environ["GROQ_API_KEY"] = api_key
315
+
316
+ # # Bhashini API setup
317
+ # bhashini_api_key = os.getenv("API_KEY")
318
+ # bhashini_user_id = os.getenv("USER_ID")
319
+
320
+ # def bhashini_translate(text: str, from_code: str = "en", to_code: str = "hi") -> dict:
321
+ # """Translates text from source language to target language using the Bhashini API."""
322
+ # if not text.strip():
323
+ # print('Input text is empty. Please provide valid text for translation.')
324
+ # return {"status_code": 400, "message": "Input text is empty", "translated_content": None}
325
+ # else:
326
+ # print('Input text - ', text)
327
+ # print(f'Starting translation process from {from_code} to {to_code}...')
328
+ # gr.Warning(f'Translating to {to_code}...')
329
 
330
+ # url = 'https://meity-auth.ulcacontrib.org/ulca/apis/v0/model/getModelsPipeline'
331
+ # headers = {
332
+ # "Content-Type": "application/json",
333
+ # "userID": bhashini_user_id,
334
+ # "ulcaApiKey": bhashini_api_key
335
+ # }
336
+ # payload = {
337
+ # "pipelineTasks": [{"taskType": "translation", "config": {"language": {"sourceLanguage": from_code, "targetLanguage": to_code}}}],
338
+ # "pipelineRequestConfig": {"pipelineId": "64392f96daac500b55c543cd"}
339
+ # }
340
 
341
+ # print('Sending initial request to get the pipeline...')
342
+ # response = requests.post(url, json=payload, headers=headers)
343
+
344
+ # if response.status_code != 200:
345
+ # print(f'Error in initial request: {response.status_code}, Response: {response.text}')
346
+ # return {"status_code": response.status_code, "message": "Error in translation request", "translated_content": None}
347
+
348
+ # print('Initial request successful, processing response...')
349
+ # response_data = response.json()
350
+ # print('Full response data:', response_data) # Debug the full response
351
+ # if "pipelineInferenceAPIEndPoint" not in response_data or "callbackUrl" not in response_data["pipelineInferenceAPIEndPoint"]:
352
+ # print('Unexpected response structure:', response_data)
353
+ # return {"status_code": 400, "message": "Unexpected API response structure", "translated_content": None}
354
+
355
+ # service_id = response_data["pipelineResponseConfig"][0]["config"][0]["serviceId"]
356
+ # callback_url = response_data["pipelineInferenceAPIEndPoint"]["callbackUrl"]
357
+
358
+ # print(f'Service ID: {service_id}, Callback URL: {callback_url}')
359
+
360
+ # headers2 = {
361
+ # "Content-Type": "application/json",
362
+ # response_data["pipelineInferenceAPIEndPoint"]["inferenceApiKey"]["name"]: response_data["pipelineInferenceAPIEndPoint"]["inferenceApiKey"]["value"]
363
+ # }
364
+ # compute_payload = {
365
+ # "pipelineTasks": [{"taskType": "translation", "config": {"language": {"sourceLanguage": from_code, "targetLanguage": to_code}, "serviceId": service_id}}],
366
+ # "inputData": {"input": [{"source": text}], "audio": [{"audioContent": None}]}
367
+ # }
368
+
369
+ # print(f'Sending translation request with text: "{text}"')
370
+ # compute_response = requests.post(callback_url, json=compute_payload, headers=headers2)
371
+
372
+ # if compute_response.status_code != 200:
373
+ # print(f'Error in translation request: {compute_response.status_code}, Response: {compute_response.text}')
374
+ # return {"status_code": compute_response.status_code, "message": "Error in translation", "translated_content": None}
375
+
376
+ # print('Translation request successful, processing translation...')
377
+ # compute_response_data = compute_response.json()
378
+ # translated_content = compute_response_data["pipelineResponse"][0]["output"][0]["target"]
379
+
380
+ # print(f'Translation successful. Translated content: "{translated_content}"')
381
+ # return {"status_code": 200, "message": "Translation successful", "translated_content": translated_content}
382
+
383
+ # # Initialize PhiData Agent
384
+ # agent = Agent(
385
+ # name="Science Education Assistant",
386
+ # role="You are a helpful science tutor for 10th-grade students",
387
+ # instructions=[
388
+ # "You are an expert science teacher specializing in 10th-grade curriculum.",
389
+ # "Provide clear, accurate, and age-appropriate explanations.",
390
+ # "Use simple language and examples that students can understand.",
391
+ # "Focus on concepts from physics, chemistry, and biology.",
392
+ # "Structure responses with headings and bullet points when helpful.",
393
+ # "Encourage learning and curiosity."
394
+ # ],
395
+ # model=Groq(id="llama3-70b-8192", api_key=api_key),
396
+ # markdown=True
397
+ # )
398
+ # # Set up Jinja2 environment
399
+ # proj_dir = Path(__file__).parent
400
+ # env = Environment(loader=FileSystemLoader(proj_dir / 'templates'))
401
+
402
+
403
+ # template_html = env.get_template('template_html.j2')
404
+
405
+ # # Response Generation Function
406
+ # def retrieve_and_generate_response(query, cross_encoder_choice, history=None):
407
+ # """Generate response using semantic search and LLM"""
408
+ # top_rerank = 25
409
+ # top_k_rank = 20
410
+
411
+ # if not query.strip():
412
+ # return "Please provide a valid question."
413
+
414
+ # try:
415
+ # start_time = perf_counter()
416
 
417
+ # # Encode query and search documents
418
+ # query_vec = retriever.encode(query)
419
+ # documents = table.search(query_vec, vector_column_name="vector").limit(top_rerank).to_list()
420
+ # documents = [doc["text"] for doc in documents]
 
 
 
 
 
421
 
422
+ # # Re-rank documents using cross-encoder
423
+ # cross_encoder_model = CrossEncoder('BAAI/bge-reranker-base') if cross_encoder_choice == '(ACCURATE) BGE reranker' else CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
424
+ # query_doc_pair = [[query, doc] for doc in documents]
425
+ # cross_scores = cross_encoder_model.predict(query_doc_pair)
426
+ # sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
427
+ # documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
428
+
429
+ # # Create context from top documents
430
+ # context = "\n\n".join(documents[:10]) if documents else ""
431
+ # context = f"Context information from educational materials:\n{context}\n\n"
432
+
433
+ # # Add conversation history for context
434
+ # history_context = ""
435
+ # if history and len(history) > 0:
436
+ # for user_msg, bot_msg in history[-2:]: # Last 2 exchanges
437
+ # if user_msg and bot_msg:
438
+ # history_context += f"Previous Q: {user_msg}\nPrevious A: {bot_msg}\n"
439
+
440
+ # # Create full prompt
441
+ # full_prompt = f"{history_context}{context}Question: {query}\n\nPlease answer the question using the context provided above. If the context doesn't contain relevant information, use your general knowledge about 10th-grade science topics."
442
+
443
+ # # Generate response
444
+ # response = agent.run(full_prompt)
445
+ # response_text = response.content if hasattr(response, 'content') else str(response)
446
+
447
+ # logger.info(f"Response generation took {perf_counter() - start_time:.2f} seconds")
448
+ # return response_text
449
+
450
+ # except Exception as e:
451
+ # logger.error(f"Error in response generation: {e}")
452
+ # return f"Error generating response: {str(e)}"
453
 
454
+ # def simple_chat_function(message, history, cross_encoder_choice):
455
+ # """Chat function with semantic search and retriever integration"""
456
+ # if not message.strip():
457
+ # return "", history
458
+
459
+ # # Generate response using the semantic search function
460
+ # response = retrieve_and_generate_response(message, cross_encoder_choice, history)
461
+
462
+ # # Add to history
463
+ # history.append([message, response])
464
+
465
+ # return "", history
466
+
467
+ # def translate_text(selected_language, history):
468
+ # """Translate the last response in history to the selected language."""
469
+ # iso_language_codes = {
470
+ # "Hindi": "hi", "Gom": "gom", "Kannada": "kn", "Dogri": "doi", "Bodo": "brx", "Urdu": "ur",
471
+ # "Tamil": "ta", "Kashmiri": "ks", "Assamese": "as", "Bengali": "bn", "Marathi": "mr",
472
+ # "Sindhi": "sd", "Maithili": "mai", "Punjabi": "pa", "Malayalam": "ml", "Manipuri": "mni",
473
+ # "Telugu": "te", "Sanskrit": "sa", "Nepali": "ne", "Santali": "sat", "Gujarati": "gu", "Odia": "or"
474
+ # }
475
+
476
+ # to_code = iso_language_codes[selected_language]
477
+ # response_text = history[-1][1] if history and history[-1][1] else ''
478
+ # print('response_text for translation', response_text)
479
+ # translation = bhashini_translate(response_text, to_code=to_code)
480
+ # return translation.get('translated_content', 'Translation failed.')
481
+
482
+ # # Gradio Interface with layout template
483
+ # with gr.Blocks(title="Science Chatbot", theme='gradio/soft') as demo:
484
+ # # Header section
485
+ # with gr.Row():
486
+ # with gr.Column(scale=10):
487
+ # gr.HTML(value="""<div style="color: #FF4500;"><h1>Welcome! I am your friend!</h1>Ask me !I will help you<h1><span style="color: #008000">I AM A CHATBOT FOR 10TH SCIENCE WITH TRANSLATION IN 22 LANGUAGES</span></h1></div>""")
488
+ # gr.HTML(value=f"""<p style="font-family: sans-serif; font-size: 16px;">A free chat bot developed by K.M.RAMYASRI,TGT,GHS.SUTHUKENY using Open source LLMs for 10 std students</p>""")
489
+ # gr.HTML(value=f"""<p style="font-family: Arial, sans-serif; font-size: 14px;"> Suggestions may be sent to <a href="mailto:[email protected]" style="color: #00008B; font-style: italic;">[email protected]</a>.</p>""")
490
+ # with gr.Column(scale=3):
491
+ # try:
492
+ # gr.Image(value='logo.png', height=200, width=200)
493
+ # except:
494
+ # gr.HTML("<div style='height: 200px; width: 200px; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center;'>Logo</div>")
495
 
496
+ # # Chat and input components
497
+ # chatbot = gr.Chatbot(
498
+ # [],
499
+ # elem_id="chatbot",
500
+ # avatar_images=('https://aui.atlassian.com/aui/8.8/docs/images/avatar-person.svg',
501
+ # 'https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.svg'),
502
+ # bubble_full_width=False,
503
+ # show_copy_button=True,
504
+ # show_share_button=True,
505
+ # )
506
+
507
+ # with gr.Row():
508
+ # msg = gr.Textbox(
509
+ # scale=3,
510
+ # show_label=False,
511
+ # placeholder="Enter text and press enter",
512
+ # container=False,
513
+ # )
514
+ # submit_btn = gr.Button(value="Submit text", scale=1, variant="primary")
515
+
516
+ # # Additional controls
517
+ # cross_encoder = gr.Radio(
518
+ # choices=['(FAST) MiniLM-L6v2', '(ACCURATE) BGE reranker'],
519
+ # value='(ACCURATE) BGE reranker',
520
+ # label="Embeddings Model",
521
+ # info="Select the model for document ranking"
522
+ # )
523
+ # language_dropdown = gr.Dropdown(
524
+ # choices=[
525
+ # "Hindi", "Gom", "Kannada", "Dogri", "Bodo", "Urdu", "Tamil", "Kashmiri", "Assamese", "Bengali", "Marathi",
526
+ # "Sindhi", "Maithili", "Punjabi", "Malayalam", "Manipuri", "Telugu", "Sanskrit", "Nepali", "Santali",
527
+ # "Gujarati", "Odia"
528
+ # ],
529
+ # value="Hindi",
530
+ # label="Select Language for Translation"
531
+ # )
532
+ # translated_textbox = gr.Textbox(label="Translated Response")
533
+
534
+ # # Event handlers
535
+ # def update_chat_and_translate(message, history, cross_encoder_choice, selected_language):
536
+ # if not message.strip():
537
+ # return "", history, ""
538
+
539
+ # # Generate response
540
+ # response = retrieve_and_generate_response(message, cross_encoder_choice, history)
541
+ # history.append([message, response])
542
+
543
+ # # Translate response
544
+ # translated_text = translate_text(selected_language, history)
545
+
546
+ # return "", history, translated_text
547
 
548
+ # msg.submit(update_chat_and_translate, [msg, chatbot, cross_encoder, language_dropdown], [msg, chatbot, translated_textbox])
549
+ # submit_btn.click(update_chat_and_translate, [msg, chatbot, cross_encoder, language_dropdown], [msg, chatbot, translated_textbox])
550
 
551
+ # clear = gr.Button("Clear Conversation")
552
+ # clear.click(lambda: ([], "", ""), outputs=[chatbot, msg, translated_textbox])
553
 
554
+ # # Example questions
555
+ # gr.Examples(
556
+ # examples=[
557
+ # 'What is the difference between metals and non-metals?',
558
+ # 'What is an ionic bond?',
559
+ # 'Explain asexual reproduction',
560
+ # 'What is photosynthesis?',
561
+ # 'Explain Newton\'s laws of motion'
562
+ # ],
563
+ # inputs=msg,
564
+ # label="Try these example questions:"
565
+ # )
566
 
567
+ # if __name__ == "__main__":
568
+ # demo.launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr