RAMYASRI-39 commited on
Commit
f3c5e9a
·
verified ·
1 Parent(s): be9a724

Update app.py

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