Spaces:
Running
Running
Upload 3 files
Browse files- app.py +147 -198
- build_vector_store.py +24 -7
- evaluate.py +1 -1
app.py
CHANGED
|
@@ -1,198 +1,147 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
|
| 4 |
-
import gradio as gr
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
self.
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
with
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
try:
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
yield history, "" # Update the chatbot UI and keep the textbox clear
|
| 149 |
-
|
| 150 |
-
# --- Your existing Gradio UI code ---
|
| 151 |
-
with gr.Blocks(
|
| 152 |
-
title="MANIT Bhopal Expert Assistant",
|
| 153 |
-
theme=gr.themes.Soft(),
|
| 154 |
-
css=""".gradio-container {max-width: 900px; margin: 0 auto;}"""
|
| 155 |
-
) as demo:
|
| 156 |
-
|
| 157 |
-
gr.Markdown("""
|
| 158 |
-
# 🎓 MANIT Bhopal Expert Assistant
|
| 159 |
-
*Powered by Advanced RAG Technology*
|
| 160 |
-
|
| 161 |
-
Ask questions about programs, admissions, faculty, facilities, research, and more.
|
| 162 |
-
""")
|
| 163 |
-
|
| 164 |
-
chatbot_ui = gr.Chatbot(
|
| 165 |
-
height=500,
|
| 166 |
-
show_label=False,
|
| 167 |
-
avatar_images=[None, "👨🎓"],
|
| 168 |
-
show_copy_button=True
|
| 169 |
-
)
|
| 170 |
-
|
| 171 |
-
with gr.Row():
|
| 172 |
-
msg = gr.Textbox(
|
| 173 |
-
label="Your Question",
|
| 174 |
-
placeholder="Ask about MANIT Bhopal...",
|
| 175 |
-
scale=8,
|
| 176 |
-
lines=2
|
| 177 |
-
)
|
| 178 |
-
submit = gr.Button("Send", scale=1, variant="primary")
|
| 179 |
-
|
| 180 |
-
gr.Examples(
|
| 181 |
-
examples=[
|
| 182 |
-
"Who is the director of MANIT?",
|
| 183 |
-
"Tell me about history of MANIT",
|
| 184 |
-
"What research facilities are available at MANIT?"
|
| 185 |
-
],
|
| 186 |
-
inputs=msg,
|
| 187 |
-
label="Example Questions"
|
| 188 |
-
)
|
| 189 |
-
|
| 190 |
-
# --- Updated event handlers for streaming ---
|
| 191 |
-
msg.submit(chat_fn, [msg, chatbot_ui], [chatbot_ui, msg])
|
| 192 |
-
submit.click(chat_fn, [msg, chatbot_ui], [chatbot_ui, msg])
|
| 193 |
-
|
| 194 |
-
return demo
|
| 195 |
-
|
| 196 |
-
if __name__ == "__main__":
|
| 197 |
-
demo = create_interface()
|
| 198 |
-
demo.launch()
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Optimized MANIT RAG Chatbot for HuggingFace Spaces"""
|
| 3 |
+
import os
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import time
|
| 6 |
+
import logging
|
| 7 |
+
from typing import List, Dict
|
| 8 |
+
import warnings
|
| 9 |
+
warnings.filterwarnings("ignore")
|
| 10 |
+
|
| 11 |
+
# Configure logging
|
| 12 |
+
logging.basicConfig(level=logging.INFO)
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
# Import your components
|
| 16 |
+
from src.retrieval.semantic_retriever import SemanticRetriever
|
| 17 |
+
from src.generation.response_generator import ResponseGenerator
|
| 18 |
+
from config.settings import config
|
| 19 |
+
|
| 20 |
+
class OptimizedMANITChatbot:
|
| 21 |
+
"""HF Space optimized chatbot"""
|
| 22 |
+
|
| 23 |
+
def __init__(self):
|
| 24 |
+
self.initialized = False
|
| 25 |
+
self.initialization_status = "Starting..."
|
| 26 |
+
self.setup_components()
|
| 27 |
+
|
| 28 |
+
def setup_components(self):
|
| 29 |
+
"""Initialize with progress tracking"""
|
| 30 |
+
try:
|
| 31 |
+
self.initialization_status = "Loading vector store..."
|
| 32 |
+
# Load your pre-built vector store components here
|
| 33 |
+
# (Same as your current implementation)
|
| 34 |
+
|
| 35 |
+
self.initialization_status = "Warming up models..."
|
| 36 |
+
# Warm up embedding model
|
| 37 |
+
self.embedding_model.encode(["warmup"], show_progress_bar=False)
|
| 38 |
+
|
| 39 |
+
self.initialization_status = "Ready!"
|
| 40 |
+
self.initialized = True
|
| 41 |
+
logger.info("MANIT Chatbot initialized successfully")
|
| 42 |
+
|
| 43 |
+
except Exception as e:
|
| 44 |
+
logger.error(f"Initialization failed: {e}")
|
| 45 |
+
self.initialization_status = f"Error: {str(e)}"
|
| 46 |
+
|
| 47 |
+
def process_query_stream(self, query: str):
|
| 48 |
+
"""Stream response with error handling"""
|
| 49 |
+
if not self.initialized:
|
| 50 |
+
yield "System is still initializing. Please wait..."
|
| 51 |
+
return
|
| 52 |
+
|
| 53 |
+
if not query.strip():
|
| 54 |
+
yield "Please enter a question about MANIT Bhopal."
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
# Your existing streaming logic
|
| 59 |
+
yield from self.generator.generate_response_stream(query, context, web_context)
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
logger.error(f"Query processing error: {e}")
|
| 63 |
+
yield "I encountered an error. Please try rephrasing your question."
|
| 64 |
+
|
| 65 |
+
def create_hf_interface():
|
| 66 |
+
"""Create HF Space optimized interface"""
|
| 67 |
+
|
| 68 |
+
# Initialize chatbot
|
| 69 |
+
chatbot_instance = OptimizedMANITChatbot()
|
| 70 |
+
|
| 71 |
+
def chat_fn(message, history):
|
| 72 |
+
"""Chat function with initialization check"""
|
| 73 |
+
if not chatbot_instance.initialized:
|
| 74 |
+
return history + [[message, f"⚠️ {chatbot_instance.initialization_status}"]], ""
|
| 75 |
+
|
| 76 |
+
# Add user message
|
| 77 |
+
history.append([message, ""])
|
| 78 |
+
|
| 79 |
+
# Stream bot response
|
| 80 |
+
for chunk in chatbot_instance.process_query_stream(message):
|
| 81 |
+
history[-1][1] += chunk
|
| 82 |
+
yield history, ""
|
| 83 |
+
|
| 84 |
+
# Custom CSS for better mobile experience
|
| 85 |
+
custom_css = """
|
| 86 |
+
.gradio-container {max-width: 900px !important; margin: 0 auto !important;}
|
| 87 |
+
.message.user {background-color: #e3f2fd !important;}
|
| 88 |
+
.message.bot {background-color: #f5f5f5 !important;}
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
with gr.Blocks(
|
| 92 |
+
title="MANIT Bhopal Expert Assistant",
|
| 93 |
+
theme=gr.themes.Soft(),
|
| 94 |
+
css=custom_css
|
| 95 |
+
) as demo:
|
| 96 |
+
|
| 97 |
+
gr.HTML("""
|
| 98 |
+
<div style="text-align: center; margin-bottom: 20px;">
|
| 99 |
+
<h1>🎓 MANIT Bhopal Expert Assistant</h1>
|
| 100 |
+
<p><em>Powered by Advanced RAG Technology</em></p>
|
| 101 |
+
<p>Ask questions about programs, admissions, faculty, facilities, research, and more.</p>
|
| 102 |
+
</div>
|
| 103 |
+
""")
|
| 104 |
+
|
| 105 |
+
chatbot_ui = gr.Chatbot(
|
| 106 |
+
height=500,
|
| 107 |
+
show_label=False,
|
| 108 |
+
avatar_images=[None, "🎓"],
|
| 109 |
+
show_copy_button=True,
|
| 110 |
+
placeholder="Hi! I'm your MANIT Bhopal assistant. Ask me anything!"
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
with gr.Row():
|
| 114 |
+
msg = gr.Textbox(
|
| 115 |
+
label="Your Question",
|
| 116 |
+
placeholder="Ask about MANIT Bhopal...",
|
| 117 |
+
scale=8,
|
| 118 |
+
lines=2,
|
| 119 |
+
max_lines=4
|
| 120 |
+
)
|
| 121 |
+
submit = gr.Button("Send", scale=1, variant="primary")
|
| 122 |
+
|
| 123 |
+
gr.Examples(
|
| 124 |
+
examples=[
|
| 125 |
+
"Who is the director of MANIT?",
|
| 126 |
+
"What are the dispensary timings?",
|
| 127 |
+
"Tell me about the computer science department",
|
| 128 |
+
"What research facilities are available?",
|
| 129 |
+
"How do I apply for admission?"
|
| 130 |
+
],
|
| 131 |
+
inputs=msg,
|
| 132 |
+
label="Example Questions"
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# Event handlers
|
| 136 |
+
msg.submit(chat_fn, [msg, chatbot_ui], [chatbot_ui, msg])
|
| 137 |
+
submit.click(chat_fn, [msg, chatbot_ui], [chatbot_ui, msg])
|
| 138 |
+
|
| 139 |
+
return demo
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
demo = create_hf_interface()
|
| 143 |
+
demo.launch(
|
| 144 |
+
server_name="0.0.0.0",
|
| 145 |
+
server_port=7860,
|
| 146 |
+
share=False
|
| 147 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
build_vector_store.py
CHANGED
|
@@ -1,31 +1,48 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
|
| 4 |
import os
|
| 5 |
import sys
|
| 6 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from config.settings import config
|
| 8 |
|
| 9 |
def main():
|
| 10 |
-
print("
|
| 11 |
|
| 12 |
# Check if raw texts exist
|
| 13 |
if not os.path.exists(config.RAW_TEXT_PATH):
|
| 14 |
print(f"Error: Raw text path {config.RAW_TEXT_PATH} does not exist")
|
| 15 |
sys.exit(1)
|
| 16 |
|
| 17 |
-
# Process
|
| 18 |
-
processor =
|
| 19 |
chunks = processor.process_directory()
|
| 20 |
|
| 21 |
if not chunks:
|
| 22 |
print("No chunks were processed. Check your input files.")
|
| 23 |
sys.exit(1)
|
| 24 |
|
| 25 |
-
print(f"Processed {len(chunks)} chunks
|
| 26 |
processor.build_vector_store(chunks)
|
| 27 |
|
| 28 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
if __name__ == "__main__":
|
| 31 |
main()
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
+
"""Rebuild vector store with optimized processing"""
|
| 3 |
|
| 4 |
import os
|
| 5 |
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
# Add the project root to Python path
|
| 9 |
+
project_root = Path(__file__).parent
|
| 10 |
+
sys.path.insert(0, str(project_root))
|
| 11 |
+
|
| 12 |
+
from src.preprocessing.advanced_processor import OptimizedTextProcessor
|
| 13 |
from config.settings import config
|
| 14 |
|
| 15 |
def main():
|
| 16 |
+
print("Rebuilding MANIT RAG Vector Store with optimized chunking...")
|
| 17 |
|
| 18 |
# Check if raw texts exist
|
| 19 |
if not os.path.exists(config.RAW_TEXT_PATH):
|
| 20 |
print(f"Error: Raw text path {config.RAW_TEXT_PATH} does not exist")
|
| 21 |
sys.exit(1)
|
| 22 |
|
| 23 |
+
# Process with optimized processor
|
| 24 |
+
processor = OptimizedTextProcessor()
|
| 25 |
chunks = processor.process_directory()
|
| 26 |
|
| 27 |
if not chunks:
|
| 28 |
print("No chunks were processed. Check your input files.")
|
| 29 |
sys.exit(1)
|
| 30 |
|
| 31 |
+
print(f"Processed {len(chunks)} optimized chunks")
|
| 32 |
processor.build_vector_store(chunks)
|
| 33 |
|
| 34 |
+
print("✅ Optimized vector store built successfully!")
|
| 35 |
+
print(f"📊 Total chunks: {len(chunks)}")
|
| 36 |
+
|
| 37 |
+
# Display chunk type distribution
|
| 38 |
+
chunk_types = {}
|
| 39 |
+
for chunk in chunks:
|
| 40 |
+
chunk_type = chunk['metadata'].get('chunk_type', 'unknown')
|
| 41 |
+
chunk_types[chunk_type] = chunk_types.get(chunk_type, 0) + 1
|
| 42 |
+
|
| 43 |
+
print("\n📈 Chunk distribution:")
|
| 44 |
+
for chunk_type, count in sorted(chunk_types.items()):
|
| 45 |
+
print(f" - {chunk_type}: {count} chunks")
|
| 46 |
|
| 47 |
if __name__ == "__main__":
|
| 48 |
main()
|
evaluate.py
CHANGED
|
@@ -29,7 +29,7 @@ def evaluate_performance():
|
|
| 29 |
"what is the name of person who registered the design for a paver block",
|
| 30 |
"What are the objective for intellectual property rights cell at manit",
|
| 31 |
"Tell me about mentorship program at MANIT",
|
| 32 |
-
"What are the recent events at
|
| 33 |
]
|
| 34 |
|
| 35 |
results = []
|
|
|
|
| 29 |
"what is the name of person who registered the design for a paver block",
|
| 30 |
"What are the objective for intellectual property rights cell at manit",
|
| 31 |
"Tell me about mentorship program at MANIT",
|
| 32 |
+
"What are the recent events at manit"
|
| 33 |
]
|
| 34 |
|
| 35 |
results = []
|