Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -51,11 +51,16 @@ def bhashini_translate(text: str, from_code: str = "en", to_code: str = "hi") ->
|
|
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}')
|
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 |
service_id = response_data["pipelineResponseConfig"][0]["config"][0]["serviceId"]
|
60 |
callback_url = response_data["pipelineInferenceAPIEndPoint"]["callbackUrl"]
|
61 |
|
@@ -74,7 +79,7 @@ def bhashini_translate(text: str, from_code: str = "en", to_code: str = "hi") ->
|
|
74 |
compute_response = requests.post(callback_url, json=compute_payload, headers=headers2)
|
75 |
|
76 |
if compute_response.status_code != 200:
|
77 |
-
print(f'Error in translation request: {compute_response.status_code}')
|
78 |
return {"status_code": compute_response.status_code, "message": "Error in translation", "translated_content": None}
|
79 |
|
80 |
print('Translation request successful, processing translation...')
|
@@ -264,6 +269,273 @@ with gr.Blocks(title="Science Chatbot", theme='gradio/soft') as demo:
|
|
264 |
|
265 |
if __name__ == "__main__":
|
266 |
demo.launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
267 |
# from phi.agent import Agent
|
268 |
# from phi.model.groq import Groq
|
269 |
# import os
|
|
|
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...')
|
|
|
269 |
|
270 |
if __name__ == "__main__":
|
271 |
demo.launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
|
272 |
+
# from phi.agent import Agent
|
273 |
+
# from phi.model.groq import Groq
|
274 |
+
# import os
|
275 |
+
# import logging
|
276 |
+
# from sentence_transformers import CrossEncoder
|
277 |
+
# from backend.semantic_search import table, retriever
|
278 |
+
# import numpy as np
|
279 |
+
# from time import perf_counter
|
280 |
+
# import requests
|
281 |
+
|
282 |
+
# # Set up logging
|
283 |
+
# logging.basicConfig(level=logging.INFO)
|
284 |
+
# logger = logging.getLogger(__name__)
|
285 |
+
|
286 |
+
# # API Key setup
|
287 |
+
# api_key = os.getenv("GROQ_API_KEY")
|
288 |
+
# if not api_key:
|
289 |
+
# gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
|
290 |
+
# logger.error("GROQ_API_KEY not found.")
|
291 |
+
# api_key = "" # Fallback to empty string, but this will fail without a key
|
292 |
+
# else:
|
293 |
+
# os.environ["GROQ_API_KEY"] = api_key
|
294 |
+
|
295 |
+
# # Bhashini API setup
|
296 |
+
# bhashini_api_key = os.getenv("API_KEY")
|
297 |
+
# bhashini_user_id = os.getenv("USER_ID")
|
298 |
+
|
299 |
+
# def bhashini_translate(text: str, from_code: str = "en", to_code: str = "hi") -> dict:
|
300 |
+
# """Translates text from source language to target language using the Bhashini API."""
|
301 |
+
# if not text.strip():
|
302 |
+
# print('Input text is empty. Please provide valid text for translation.')
|
303 |
+
# return {"status_code": 400, "message": "Input text is empty", "translated_content": None}
|
304 |
+
# else:
|
305 |
+
# print('Input text - ', text)
|
306 |
+
# print(f'Starting translation process from {from_code} to {to_code}...')
|
307 |
+
# gr.Warning(f'Translating to {to_code}...')
|
308 |
+
|
309 |
+
# url = 'https://meity-auth.ulcacontrib.org/ulca/apis/v0/model/getModelsPipeline'
|
310 |
+
# headers = {
|
311 |
+
# "Content-Type": "application/json",
|
312 |
+
# "userID": bhashini_user_id,
|
313 |
+
# "ulcaApiKey": bhashini_api_key
|
314 |
+
# }
|
315 |
+
# payload = {
|
316 |
+
# "pipelineTasks": [{"taskType": "translation", "config": {"language": {"sourceLanguage": from_code, "targetLanguage": to_code}}}],
|
317 |
+
# "pipelineRequestConfig": {"pipelineId": "64392f96daac500b55c543cd"}
|
318 |
+
# }
|
319 |
+
|
320 |
+
# print('Sending initial request to get the pipeline...')
|
321 |
+
# response = requests.post(url, json=payload, headers=headers)
|
322 |
+
|
323 |
+
# if response.status_code != 200:
|
324 |
+
# print(f'Error in initial request: {response.status_code}')
|
325 |
+
# return {"status_code": response.status_code, "message": "Error in translation request", "translated_content": None}
|
326 |
+
|
327 |
+
# print('Initial request successful, processing response...')
|
328 |
+
# response_data = response.json()
|
329 |
+
# service_id = response_data["pipelineResponseConfig"][0]["config"][0]["serviceId"]
|
330 |
+
# callback_url = response_data["pipelineInferenceAPIEndPoint"]["callbackUrl"]
|
331 |
+
|
332 |
+
# print(f'Service ID: {service_id}, Callback URL: {callback_url}')
|
333 |
+
|
334 |
+
# headers2 = {
|
335 |
+
# "Content-Type": "application/json",
|
336 |
+
# response_data["pipelineInferenceAPIEndPoint"]["inferenceApiKey"]["name"]: response_data["pipelineInferenceAPIEndPoint"]["inferenceApiKey"]["value"]
|
337 |
+
# }
|
338 |
+
# compute_payload = {
|
339 |
+
# "pipelineTasks": [{"taskType": "translation", "config": {"language": {"sourceLanguage": from_code, "targetLanguage": to_code}, "serviceId": service_id}}],
|
340 |
+
# "inputData": {"input": [{"source": text}], "audio": [{"audioContent": None}]}
|
341 |
+
# }
|
342 |
+
|
343 |
+
# print(f'Sending translation request with text: "{text}"')
|
344 |
+
# compute_response = requests.post(callback_url, json=compute_payload, headers=headers2)
|
345 |
+
|
346 |
+
# if compute_response.status_code != 200:
|
347 |
+
# print(f'Error in translation request: {compute_response.status_code}')
|
348 |
+
# return {"status_code": compute_response.status_code, "message": "Error in translation", "translated_content": None}
|
349 |
+
|
350 |
+
# print('Translation request successful, processing translation...')
|
351 |
+
# compute_response_data = compute_response.json()
|
352 |
+
# translated_content = compute_response_data["pipelineResponse"][0]["output"][0]["target"]
|
353 |
+
|
354 |
+
# print(f'Translation successful. Translated content: "{translated_content}"')
|
355 |
+
# return {"status_code": 200, "message": "Translation successful", "translated_content": translated_content}
|
356 |
+
|
357 |
+
# # Initialize PhiData Agent
|
358 |
+
# agent = Agent(
|
359 |
+
# name="Science Education Assistant",
|
360 |
+
# role="You are a helpful science tutor for 10th-grade students",
|
361 |
+
# instructions=[
|
362 |
+
# "You are an expert science teacher specializing in 10th-grade curriculum.",
|
363 |
+
# "Provide clear, accurate, and age-appropriate explanations.",
|
364 |
+
# "Use simple language and examples that students can understand.",
|
365 |
+
# "Focus on concepts from physics, chemistry, and biology.",
|
366 |
+
# "Structure responses with headings and bullet points when helpful.",
|
367 |
+
# "Encourage learning and curiosity."
|
368 |
+
# ],
|
369 |
+
# model=Groq(id="llama3-70b-8192", api_key=api_key),
|
370 |
+
# markdown=True
|
371 |
+
# )
|
372 |
+
|
373 |
+
# # Response Generation Function
|
374 |
+
# def retrieve_and_generate_response(query, cross_encoder_choice, history=None):
|
375 |
+
# """Generate response using semantic search and LLM"""
|
376 |
+
# top_rerank = 25
|
377 |
+
# top_k_rank = 20
|
378 |
+
|
379 |
+
# if not query.strip():
|
380 |
+
# return "Please provide a valid question."
|
381 |
+
|
382 |
+
# try:
|
383 |
+
# start_time = perf_counter()
|
384 |
+
|
385 |
+
# # Encode query and search documents
|
386 |
+
# query_vec = retriever.encode(query)
|
387 |
+
# documents = table.search(query_vec, vector_column_name="vector").limit(top_rerank).to_list()
|
388 |
+
# documents = [doc["text"] for doc in documents]
|
389 |
+
|
390 |
+
# # Re-rank documents using cross-encoder
|
391 |
+
# 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')
|
392 |
+
# query_doc_pair = [[query, doc] for doc in documents]
|
393 |
+
# cross_scores = cross_encoder_model.predict(query_doc_pair)
|
394 |
+
# sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
|
395 |
+
# documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
|
396 |
+
|
397 |
+
# # Create context from top documents
|
398 |
+
# context = "\n\n".join(documents[:10]) if documents else ""
|
399 |
+
# context = f"Context information from educational materials:\n{context}\n\n"
|
400 |
+
|
401 |
+
# # Add conversation history for context
|
402 |
+
# history_context = ""
|
403 |
+
# if history and len(history) > 0:
|
404 |
+
# for user_msg, bot_msg in history[-2:]: # Last 2 exchanges
|
405 |
+
# if user_msg and bot_msg:
|
406 |
+
# history_context += f"Previous Q: {user_msg}\nPrevious A: {bot_msg}\n"
|
407 |
+
|
408 |
+
# # Create full prompt
|
409 |
+
# 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."
|
410 |
+
|
411 |
+
# # Generate response
|
412 |
+
# response = agent.run(full_prompt)
|
413 |
+
# response_text = response.content if hasattr(response, 'content') else str(response)
|
414 |
+
|
415 |
+
# logger.info(f"Response generation took {perf_counter() - start_time:.2f} seconds")
|
416 |
+
# return response_text
|
417 |
+
|
418 |
+
# except Exception as e:
|
419 |
+
# logger.error(f"Error in response generation: {e}")
|
420 |
+
# return f"Error generating response: {str(e)}"
|
421 |
+
|
422 |
+
# def simple_chat_function(message, history, cross_encoder_choice):
|
423 |
+
# """Chat function with semantic search and retriever integration"""
|
424 |
+
# if not message.strip():
|
425 |
+
# return "", history
|
426 |
+
|
427 |
+
# # Generate response using the semantic search function
|
428 |
+
# response = retrieve_and_generate_response(message, cross_encoder_choice, history)
|
429 |
+
|
430 |
+
# # Add to history
|
431 |
+
# history.append([message, response])
|
432 |
+
|
433 |
+
# return "", history
|
434 |
+
|
435 |
+
# def translate_text(selected_language, history):
|
436 |
+
# """Translate the last response in history to the selected language."""
|
437 |
+
# iso_language_codes = {
|
438 |
+
# "Hindi": "hi", "Gom": "gom", "Kannada": "kn", "Dogri": "doi", "Bodo": "brx", "Urdu": "ur",
|
439 |
+
# "Tamil": "ta", "Kashmiri": "ks", "Assamese": "as", "Bengali": "bn", "Marathi": "mr",
|
440 |
+
# "Sindhi": "sd", "Maithili": "mai", "Punjabi": "pa", "Malayalam": "ml", "Manipuri": "mni",
|
441 |
+
# "Telugu": "te", "Sanskrit": "sa", "Nepali": "ne", "Santali": "sat", "Gujarati": "gu", "Odia": "or"
|
442 |
+
# }
|
443 |
+
|
444 |
+
# to_code = iso_language_codes[selected_language]
|
445 |
+
# response_text = history[-1][1] if history and history[-1][1] else ''
|
446 |
+
# print('response_text for translation', response_text)
|
447 |
+
# translation = bhashini_translate(response_text, to_code=to_code)
|
448 |
+
# return translation.get('translated_content', 'Translation failed.')
|
449 |
+
|
450 |
+
# # Gradio Interface with layout template
|
451 |
+
# with gr.Blocks(title="Science Chatbot", theme='gradio/soft') as demo:
|
452 |
+
# # Header section
|
453 |
+
# with gr.Row():
|
454 |
+
# with gr.Column(scale=10):
|
455 |
+
# 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>""")
|
456 |
+
# 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>""")
|
457 |
+
# 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>""")
|
458 |
+
# with gr.Column(scale=3):
|
459 |
+
# try:
|
460 |
+
# gr.Image(value='logo.png', height=200, width=200)
|
461 |
+
# except:
|
462 |
+
# gr.HTML("<div style='height: 200px; width: 200px; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center;'>Logo</div>")
|
463 |
+
|
464 |
+
# # Chat and input components
|
465 |
+
# chatbot = gr.Chatbot(
|
466 |
+
# [],
|
467 |
+
# elem_id="chatbot",
|
468 |
+
# avatar_images=('https://aui.atlassian.com/aui/8.8/docs/images/avatar-person.svg',
|
469 |
+
# 'https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.svg'),
|
470 |
+
# bubble_full_width=False,
|
471 |
+
# show_copy_button=True,
|
472 |
+
# show_share_button=True,
|
473 |
+
# )
|
474 |
+
|
475 |
+
# with gr.Row():
|
476 |
+
# msg = gr.Textbox(
|
477 |
+
# scale=3,
|
478 |
+
# show_label=False,
|
479 |
+
# placeholder="Enter text and press enter",
|
480 |
+
# container=False,
|
481 |
+
# )
|
482 |
+
# submit_btn = gr.Button(value="Submit text", scale=1, variant="primary")
|
483 |
+
|
484 |
+
# # Additional controls
|
485 |
+
# cross_encoder = gr.Radio(
|
486 |
+
# choices=['(FAST) MiniLM-L6v2', '(ACCURATE) BGE reranker'],
|
487 |
+
# value='(ACCURATE) BGE reranker',
|
488 |
+
# label="Embeddings Model",
|
489 |
+
# info="Select the model for document ranking"
|
490 |
+
# )
|
491 |
+
# language_dropdown = gr.Dropdown(
|
492 |
+
# choices=[
|
493 |
+
# "Hindi", "Gom", "Kannada", "Dogri", "Bodo", "Urdu", "Tamil", "Kashmiri", "Assamese", "Bengali", "Marathi",
|
494 |
+
# "Sindhi", "Maithili", "Punjabi", "Malayalam", "Manipuri", "Telugu", "Sanskrit", "Nepali", "Santali",
|
495 |
+
# "Gujarati", "Odia"
|
496 |
+
# ],
|
497 |
+
# value="Hindi",
|
498 |
+
# label="Select Language for Translation"
|
499 |
+
# )
|
500 |
+
# translated_textbox = gr.Textbox(label="Translated Response")
|
501 |
+
|
502 |
+
# # Event handlers
|
503 |
+
# def update_chat_and_translate(message, history, cross_encoder_choice, selected_language):
|
504 |
+
# if not message.strip():
|
505 |
+
# return "", history, ""
|
506 |
+
|
507 |
+
# # Generate response
|
508 |
+
# response = retrieve_and_generate_response(message, cross_encoder_choice, history)
|
509 |
+
# history.append([message, response])
|
510 |
+
|
511 |
+
# # Translate response
|
512 |
+
# translated_text = translate_text(selected_language, history)
|
513 |
+
|
514 |
+
# return "", history, translated_text
|
515 |
+
|
516 |
+
# msg.submit(update_chat_and_translate, [msg, chatbot, cross_encoder, language_dropdown], [msg, chatbot, translated_textbox])
|
517 |
+
# submit_btn.click(update_chat_and_translate, [msg, chatbot, cross_encoder, language_dropdown], [msg, chatbot, translated_textbox])
|
518 |
+
|
519 |
+
# clear = gr.Button("Clear Conversation")
|
520 |
+
# clear.click(lambda: ([], "", ""), outputs=[chatbot, msg, translated_textbox])
|
521 |
+
|
522 |
+
# # Example questions
|
523 |
+
# gr.Examples(
|
524 |
+
# examples=[
|
525 |
+
# 'What is the difference between metals and non-metals?',
|
526 |
+
# 'What is an ionic bond?',
|
527 |
+
# 'Explain asexual reproduction',
|
528 |
+
# 'What is photosynthesis?',
|
529 |
+
# 'Explain Newton\'s laws of motion'
|
530 |
+
# ],
|
531 |
+
# inputs=msg,
|
532 |
+
# label="Try these example questions:"
|
533 |
+
# )
|
534 |
+
|
535 |
+
# if __name__ == "__main__":
|
536 |
+
# demo.launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
|
537 |
+
|
538 |
+
|
539 |
# from phi.agent import Agent
|
540 |
# from phi.model.groq import Groq
|
541 |
# import os
|