Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -84,38 +84,86 @@ def retrieve_and_generate_response(query, cross_encoder_choice, history=None):
|
|
| 84 |
return f"Error: {str(e)}"
|
| 85 |
|
| 86 |
# Gradio Interface with Chatbot
|
| 87 |
-
with gr.Blocks(title="Science Chatbot", theme=
|
| 88 |
-
gr.
|
| 89 |
-
<center>
|
| 90 |
-
<h1><span style="color: purple;">Science Chatbot for 10th Grade Students</span></h1>
|
| 91 |
-
<h2>AI-powered Science Tutor</h2>
|
| 92 |
-
<i>⚠️ Ask any question from 10th-grade science (physics, chemistry, biology) and get clear, accurate answers! ⚠️</i>
|
| 93 |
-
</center>
|
| 94 |
-
""")
|
| 95 |
-
|
| 96 |
-
chatbot = gr.Chatbot(label="Conversation")
|
| 97 |
with gr.Row():
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
def handle_query(
|
| 104 |
-
if not
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
history.append(
|
|
|
|
|
|
|
|
|
|
| 109 |
return history, ""
|
| 110 |
|
| 111 |
submit_btn.click(
|
| 112 |
fn=handle_query,
|
| 113 |
-
inputs=[query,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
outputs=[chatbot, query]
|
| 115 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
if __name__ == "__main__":
|
| 118 |
-
chatbot_app.
|
| 119 |
# import logging
|
| 120 |
# from sentence_transformers import CrossEncoder
|
| 121 |
# from phi.agent import Agent
|
|
@@ -200,6 +248,123 @@ if __name__ == "__main__":
|
|
| 200 |
# logger.error(f"Error in response generation: {e}")
|
| 201 |
# return f"Error: {str(e)}"
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
# # Gradio Interface (Inspired by Quiz App)
|
| 204 |
# with gr.Blocks(title="Science Chatbot", theme=gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")) as chatbot_app:
|
| 205 |
# gr.HTML("""
|
|
|
|
| 84 |
return f"Error: {str(e)}"
|
| 85 |
|
| 86 |
# Gradio Interface with Chatbot
|
| 87 |
+
with gr.Blocks(title="Science Chatbot", theme='gradio/soft') as chatbot_app:
|
| 88 |
+
history_state = gr.State([])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
with gr.Row():
|
| 90 |
+
with gr.Column(scale=10):
|
| 91 |
+
gr.HTML("""
|
| 92 |
+
<div style="color: #FF4500;">
|
| 93 |
+
<h1>Welcome! I am your friend!</h1>
|
| 94 |
+
<h1>Ask me! I will help you</h1>
|
| 95 |
+
<h1><span style="color: #008000">I AM A CHATBOT FOR 10TH SCIENCE</span></h1>
|
| 96 |
+
</div>
|
| 97 |
+
<p style="font-family: sans-serif; font-size: 16px;">
|
| 98 |
+
A free chatbot developed by K.M.RAMYASRI, TGT, GHS.SUTHUKENY using Phi Agent & Groq LLMs for 10th-grade students
|
| 99 |
+
</p>
|
| 100 |
+
<p style="font-family: Arial, sans-serif; font-size: 14px;">
|
| 101 |
+
Suggestions may be sent to <a href="mailto:ramyasriraman2019@gmail.com" style="color: #00008B; font-style: italic;">ramyadevi1607@yahoo.com</a>.
|
| 102 |
+
</p>
|
| 103 |
+
""")
|
| 104 |
+
with gr.Column(scale=3):
|
| 105 |
+
gr.Image(value='logo.png', height=200, width=200, show_label=False)
|
| 106 |
|
| 107 |
+
chatbot = gr.Chatbot(
|
| 108 |
+
[],
|
| 109 |
+
elem_id="chatbot",
|
| 110 |
+
avatar_images=(
|
| 111 |
+
'https://aui.atlassian.com/aui/8.8/docs/images/avatar-person.svg',
|
| 112 |
+
'https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.svg'
|
| 113 |
+
),
|
| 114 |
+
bubble_full_width=False,
|
| 115 |
+
show_copy_button=True,
|
| 116 |
+
show_share_button=True,
|
| 117 |
+
label="Conversation"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
with gr.Row():
|
| 121 |
+
query = gr.Textbox(
|
| 122 |
+
scale=3,
|
| 123 |
+
show_label=False,
|
| 124 |
+
placeholder="Enter text and press enter",
|
| 125 |
+
container=False
|
| 126 |
+
)
|
| 127 |
+
submit_btn = gr.Button(value="Submit", scale=1, variant="primary")
|
| 128 |
+
|
| 129 |
+
cross_encoder = gr.Radio(
|
| 130 |
+
choices=['(FAST) MiniLM-L6v2', '(ACCURATE) BGE reranker'],
|
| 131 |
+
value='(ACCURATE) BGE reranker',
|
| 132 |
+
label="Embeddings",
|
| 133 |
+
info="Select the model for document ranking"
|
| 134 |
+
)
|
| 135 |
|
| 136 |
+
def handle_query(txt, cross_encoder, history_state):
|
| 137 |
+
if not txt.strip():
|
| 138 |
+
gr.Warning("Please submit a non-empty question")
|
| 139 |
+
return history_state, ""
|
| 140 |
+
history = history_state or []
|
| 141 |
+
history.append((txt, ""))
|
| 142 |
+
response = retrieve_and_generate_response(txt, cross_encoder, history[:-1])
|
| 143 |
+
history[-1] = (txt, response)
|
| 144 |
+
history_state[:] = history
|
| 145 |
return history, ""
|
| 146 |
|
| 147 |
submit_btn.click(
|
| 148 |
fn=handle_query,
|
| 149 |
+
inputs=[query, cross_encoder, history_state],
|
| 150 |
+
outputs=[chatbot, query]
|
| 151 |
+
)
|
| 152 |
+
query.submit(
|
| 153 |
+
fn=handle_query,
|
| 154 |
+
inputs=[query, cross_encoder, history_state],
|
| 155 |
outputs=[chatbot, query]
|
| 156 |
)
|
| 157 |
+
|
| 158 |
+
examples = [
|
| 159 |
+
'CAN U SAY THE DIFFERENCES BETWEEN METALS AND NON METALS?',
|
| 160 |
+
'WHAT IS IONIC BOND?',
|
| 161 |
+
'EXPLAIN ASEXUAL REPRODUCTION'
|
| 162 |
+
]
|
| 163 |
+
gr.Examples(examples, query)
|
| 164 |
|
| 165 |
if __name__ == "__main__":
|
| 166 |
+
chatbot_app.launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
|
| 167 |
# import logging
|
| 168 |
# from sentence_transformers import CrossEncoder
|
| 169 |
# from phi.agent import Agent
|
|
|
|
| 248 |
# logger.error(f"Error in response generation: {e}")
|
| 249 |
# return f"Error: {str(e)}"
|
| 250 |
|
| 251 |
+
# # Gradio Interface with Chatbot
|
| 252 |
+
# with gr.Blocks(title="Science Chatbot", theme=gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")) as chatbot_app:
|
| 253 |
+
# gr.HTML("""
|
| 254 |
+
# <center>
|
| 255 |
+
# <h1><span style="color: purple;">Science Chatbot for 10th Grade Students</span></h1>
|
| 256 |
+
# <h2>AI-powered Science Tutor</h2>
|
| 257 |
+
# <i>⚠️ Ask any question from 10th-grade science (physics, chemistry, biology) and get clear, accurate answers! ⚠️</i>
|
| 258 |
+
# </center>
|
| 259 |
+
# """)
|
| 260 |
+
|
| 261 |
+
# chatbot = gr.Chatbot(label="Conversation")
|
| 262 |
+
# with gr.Row():
|
| 263 |
+
# query = gr.Textbox(label="Ask a Science Question", placeholder="E.g., What is an ionic bond?", show_label=False)
|
| 264 |
+
# submit_btn = gr.Button("Submit", variant="primary")
|
| 265 |
+
|
| 266 |
+
# cross_encoder = gr.Radio(choices=['(FAST) MiniLM-L6v2', '(ACCURATE) BGE reranker'], value='(ACCURATE) BGE reranker', label="Embeddings")
|
| 267 |
+
|
| 268 |
+
# def handle_query(user_input, history, cross_encoder_choice):
|
| 269 |
+
# if not user_input.strip():
|
| 270 |
+
# return history, ""
|
| 271 |
+
# history = history or []
|
| 272 |
+
# response = retrieve_and_generate_response(user_input, cross_encoder_choice, history)
|
| 273 |
+
# history.append([user_input, response])
|
| 274 |
+
# return history, ""
|
| 275 |
+
|
| 276 |
+
# submit_btn.click(
|
| 277 |
+
# fn=handle_query,
|
| 278 |
+
# inputs=[query, chatbot, cross_encoder],
|
| 279 |
+
# outputs=[chatbot, query]
|
| 280 |
+
# )
|
| 281 |
+
|
| 282 |
+
# if __name__ == "__main__":
|
| 283 |
+
# chatbot_app.queue().launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
|
| 284 |
+
# # import logging
|
| 285 |
+
# from sentence_transformers import CrossEncoder
|
| 286 |
+
# from phi.agent import Agent
|
| 287 |
+
# from phi.model.groq import Groq
|
| 288 |
+
# from backend.semantic_search import table, retriever
|
| 289 |
+
# import numpy as np
|
| 290 |
+
# from time import perf_counter
|
| 291 |
+
# import os
|
| 292 |
+
|
| 293 |
+
# # Logging setup
|
| 294 |
+
# logging.basicConfig(level=logging.INFO)
|
| 295 |
+
# logger = logging.getLogger(__name__)
|
| 296 |
+
|
| 297 |
+
# # API Key setup
|
| 298 |
+
# api_key = os.getenv("GROQ_API_KEY")
|
| 299 |
+
# if not api_key:
|
| 300 |
+
# logger.error("GROQ_API_KEY not found.")
|
| 301 |
+
# gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
|
| 302 |
+
# else:
|
| 303 |
+
# os.environ["GROQ_API_KEY"] = api_key
|
| 304 |
+
|
| 305 |
+
# # Initialize Phi Agent
|
| 306 |
+
# def create_phi_agent():
|
| 307 |
+
# if not api_key:
|
| 308 |
+
# return None
|
| 309 |
+
# agent = Agent(
|
| 310 |
+
# name="Science Education Assistant",
|
| 311 |
+
# role="You are a helpful science tutor for 10th-grade students",
|
| 312 |
+
# instructions=[
|
| 313 |
+
# "You are an expert science teacher specializing in 10th-grade curriculum.",
|
| 314 |
+
# "Provide clear, accurate, and age-appropriate explanations.",
|
| 315 |
+
# "Use simple language and examples that students can understand.",
|
| 316 |
+
# "Focus on concepts from physics, chemistry, and biology.",
|
| 317 |
+
# "Structure responses with headings and bullet points when helpful.",
|
| 318 |
+
# "Encourage learning and curiosity."
|
| 319 |
+
# ],
|
| 320 |
+
# model=Groq(id="llama3-70b-8192", api_key=api_key),
|
| 321 |
+
# markdown=True
|
| 322 |
+
# )
|
| 323 |
+
# return agent
|
| 324 |
+
|
| 325 |
+
# phi_agent = create_phi_agent()
|
| 326 |
+
|
| 327 |
+
# # Response Generation
|
| 328 |
+
# def retrieve_and_generate_response(query, cross_encoder_choice, history=None):
|
| 329 |
+
# top_rerank = 25
|
| 330 |
+
# top_k_rank = 20
|
| 331 |
+
|
| 332 |
+
# if not query:
|
| 333 |
+
# return "Please provide a valid question."
|
| 334 |
+
|
| 335 |
+
# try:
|
| 336 |
+
# start_time = perf_counter()
|
| 337 |
+
# query_vec = retriever.encode(query)
|
| 338 |
+
# documents = table.search(query_vec, vector_column_name="vector").limit(top_rerank).to_list()
|
| 339 |
+
# documents = [doc["text"] for doc in documents]
|
| 340 |
+
|
| 341 |
+
# cross_encoder1 = CrossEncoder('BAAI/bge-reranker-base') if cross_encoder_choice == '(ACCURATE) BGE reranker' else CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
|
| 342 |
+
# query_doc_pair = [[query, doc] for doc in documents]
|
| 343 |
+
# cross_scores = cross_encoder1.predict(query_doc_pair)
|
| 344 |
+
# sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
|
| 345 |
+
# documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
|
| 346 |
+
|
| 347 |
+
# context = "\n\n".join(documents[:10]) if documents else ""
|
| 348 |
+
# context = f"Context information from educational materials:\n{context}\n\n"
|
| 349 |
+
|
| 350 |
+
# history_context = ""
|
| 351 |
+
# if history:
|
| 352 |
+
# for user_msg, bot_msg in history[-2:]:
|
| 353 |
+
# if user_msg and bot_msg:
|
| 354 |
+
# history_context += f"Previous Q: {user_msg}\nPrevious A: {bot_msg}\n\n"
|
| 355 |
+
|
| 356 |
+
# 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."
|
| 357 |
+
|
| 358 |
+
# if not phi_agent:
|
| 359 |
+
# return "Chatbot not configured properly."
|
| 360 |
+
# response = phi_agent.run(full_prompt)
|
| 361 |
+
# logger.info(f"Response generation took {perf_counter() - start_time:.2f} seconds")
|
| 362 |
+
# return response.content if hasattr(response, 'content') else str(response)
|
| 363 |
+
|
| 364 |
+
# except Exception as e:
|
| 365 |
+
# logger.error(f"Error in response generation: {e}")
|
| 366 |
+
# return f"Error: {str(e)}"
|
| 367 |
+
|
| 368 |
# # Gradio Interface (Inspired by Quiz App)
|
| 369 |
# with gr.Blocks(title="Science Chatbot", theme=gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")) as chatbot_app:
|
| 370 |
# gr.HTML("""
|