Spaces:
Sleeping
Sleeping
ashish-ninehertz
commited on
Commit
·
f05a666
1
Parent(s):
a0671ab
minor changes
Browse files
app.py
DELETED
|
@@ -1,283 +0,0 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import uuid
|
| 3 |
-
import logging
|
| 4 |
-
from typing import List, Tuple
|
| 5 |
-
from app.main import RAGSystem
|
| 6 |
-
import asyncio
|
| 7 |
-
|
| 8 |
-
# Configure logging
|
| 9 |
-
logging.basicConfig(level=logging.INFO)
|
| 10 |
-
logger = logging.getLogger(__name__)
|
| 11 |
-
|
| 12 |
-
# Initialize the RAG system
|
| 13 |
-
rag = RAGSystem()
|
| 14 |
-
|
| 15 |
-
def create_session() -> str:
|
| 16 |
-
"""Create a new session ID"""
|
| 17 |
-
return str(uuid.uuid4())
|
| 18 |
-
|
| 19 |
-
def index_website(url: str, session_id: str) -> Tuple[bool, str]:
|
| 20 |
-
"""Index a website for a given session"""
|
| 21 |
-
try:
|
| 22 |
-
result = rag.crawl_and_index(session_id, url)
|
| 23 |
-
if result["status"] == "success":
|
| 24 |
-
return True, f"Successfully indexed {len(result.get('urls_processed', []))} pages"
|
| 25 |
-
return False, result.get("message", "Unknown error during indexing")
|
| 26 |
-
except Exception as e:
|
| 27 |
-
logger.error(f"Indexing error: {str(e)}")
|
| 28 |
-
return False, f"Error during indexing: {str(e)}"
|
| 29 |
-
|
| 30 |
-
def chat_response(
|
| 31 |
-
session_id: str,
|
| 32 |
-
message: str,
|
| 33 |
-
model_choice: str,
|
| 34 |
-
ollama_url: str,
|
| 35 |
-
gemini_api_key: str,
|
| 36 |
-
chat_history: List[Tuple[str, str]]
|
| 37 |
-
) -> Tuple[List[Tuple[str, str]], str]:
|
| 38 |
-
"""Generate a chat response with proper error handling"""
|
| 39 |
-
if not session_id:
|
| 40 |
-
chat_history.append(("🧑 " + message, "🤖 Please index a website first or enter a valid session ID"))
|
| 41 |
-
return chat_history, ""
|
| 42 |
-
|
| 43 |
-
try:
|
| 44 |
-
response = asyncio.run(rag.chat(
|
| 45 |
-
session_id=session_id,
|
| 46 |
-
question=message,
|
| 47 |
-
model=model_choice.lower(),
|
| 48 |
-
ollama_url=ollama_url if model_choice == "mistral" else None,
|
| 49 |
-
gemini_api_key=gemini_api_key if model_choice == "gemini" else None
|
| 50 |
-
))
|
| 51 |
-
|
| 52 |
-
if response["status"] == "success":
|
| 53 |
-
answer = response["response"]
|
| 54 |
-
sources = "\n\nSources:\n" + "\n".join(
|
| 55 |
-
f"- {src['source_url']}" for src in response.get("sources", [])
|
| 56 |
-
) if response.get("sources") else ""
|
| 57 |
-
full_response = answer + sources
|
| 58 |
-
else:
|
| 59 |
-
full_response = f"Error: {response.get('message', 'Unknown error')}"
|
| 60 |
-
|
| 61 |
-
chat_history.append(("🧑 " + message, "🤖 " + full_response))
|
| 62 |
-
return chat_history, ""
|
| 63 |
-
except Exception as e:
|
| 64 |
-
logger.error(f"Chat error: {str(e)}")
|
| 65 |
-
chat_history.append(("🧑 " + message, f"🤖 System error: {str(e)}"))
|
| 66 |
-
return chat_history, ""
|
| 67 |
-
|
| 68 |
-
def toggle_model_inputs(model_choice: str) -> List[gr.update]:
|
| 69 |
-
"""Show/hide model-specific inputs"""
|
| 70 |
-
if model_choice == "mistral":
|
| 71 |
-
return [gr.update(visible=True), gr.update(visible=False)]
|
| 72 |
-
return [gr.update(visible=False), gr.update(visible=True)]
|
| 73 |
-
|
| 74 |
-
def load_session(existing_session_id: str) -> Tuple[str, str]:
|
| 75 |
-
"""Load an existing session"""
|
| 76 |
-
if existing_session_id:
|
| 77 |
-
# Here you might want to add validation if the session exists
|
| 78 |
-
return existing_session_id, f"Loaded existing session: {existing_session_id}"
|
| 79 |
-
return "", "Please enter a valid session ID"
|
| 80 |
-
|
| 81 |
-
def get_session(self, session_id: str):
|
| 82 |
-
# If session exists in memory, return it
|
| 83 |
-
if session_id in self.sessions:
|
| 84 |
-
return self.sessions[session_id]
|
| 85 |
-
# If not, check if Qdrant collection exists and has documents
|
| 86 |
-
collection_name = self.get_collection_name(session_id)
|
| 87 |
-
try:
|
| 88 |
-
results = self.qdrant_client.scroll(collection_name=collection_name, limit=1)
|
| 89 |
-
if results and results[0]:
|
| 90 |
-
# Rehydrate session in memory
|
| 91 |
-
self.sessions[session_id] = {
|
| 92 |
-
"documents": [], # Optionally, you can fetch all docs if needed
|
| 93 |
-
"history": []
|
| 94 |
-
}
|
| 95 |
-
return self.sessions[session_id]
|
| 96 |
-
except Exception as e:
|
| 97 |
-
logger.warning(f"Session {session_id} not found in Qdrant: {e}")
|
| 98 |
-
# If not found, return None or raise
|
| 99 |
-
raise ValueError("No documents indexed for this session")
|
| 100 |
-
|
| 101 |
-
# Custom CSS for better styling
|
| 102 |
-
custom_css = """
|
| 103 |
-
.gradio-container {
|
| 104 |
-
max-width: 1200px !important;
|
| 105 |
-
margin: 0 auto !important;
|
| 106 |
-
}
|
| 107 |
-
.dark .gradio-container {
|
| 108 |
-
background: #1e1e2e !important;
|
| 109 |
-
}
|
| 110 |
-
#chatbot {
|
| 111 |
-
min-height: 500px;
|
| 112 |
-
border-radius: 12px !important;
|
| 113 |
-
}
|
| 114 |
-
.message.user {
|
| 115 |
-
border-left: 4px solid #4f46e5 !important;
|
| 116 |
-
}
|
| 117 |
-
.message.assistant {
|
| 118 |
-
border-left: 4px solid #10b981 !important;
|
| 119 |
-
}
|
| 120 |
-
.btn-primary {
|
| 121 |
-
background: linear-gradient(to right, #4f46e5, #7c3aed) !important;
|
| 122 |
-
border: none !important;
|
| 123 |
-
}
|
| 124 |
-
.btn-primary:hover {
|
| 125 |
-
background: linear-gradient(to right, #4338ca, #6d28d9) !important;
|
| 126 |
-
}
|
| 127 |
-
.prose {
|
| 128 |
-
max-width: 100% !important;
|
| 129 |
-
}
|
| 130 |
-
"""
|
| 131 |
-
|
| 132 |
-
with gr.Blocks(title="RAG Chat with Mistral/Gemini", css=custom_css, theme="soft") as demo:
|
| 133 |
-
# Header section
|
| 134 |
-
with gr.Row():
|
| 135 |
-
gr.Markdown("""
|
| 136 |
-
# 🌐 RAG Chat Assistant
|
| 137 |
-
### Chat with any website using Mistral or Gemini
|
| 138 |
-
""")
|
| 139 |
-
|
| 140 |
-
# Session state
|
| 141 |
-
session_id = gr.State("")
|
| 142 |
-
|
| 143 |
-
with gr.Tabs():
|
| 144 |
-
with gr.TabItem("📚 Index Website"):
|
| 145 |
-
with gr.Row():
|
| 146 |
-
with gr.Column():
|
| 147 |
-
gr.Markdown("### Step 1: Configure and Index")
|
| 148 |
-
with gr.Group():
|
| 149 |
-
url_input = gr.Textbox(
|
| 150 |
-
label="Website URL to index",
|
| 151 |
-
placeholder="https://example.com",
|
| 152 |
-
interactive=True,
|
| 153 |
-
lines=1
|
| 154 |
-
)
|
| 155 |
-
|
| 156 |
-
with gr.Row():
|
| 157 |
-
model_choice = gr.Radio(
|
| 158 |
-
choices=["mistral", "gemini"],
|
| 159 |
-
label="Select Model",
|
| 160 |
-
value="mistral",
|
| 161 |
-
interactive=True
|
| 162 |
-
)
|
| 163 |
-
|
| 164 |
-
index_btn = gr.Button(
|
| 165 |
-
"🚀 Index Website",
|
| 166 |
-
variant="primary",
|
| 167 |
-
scale=0
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
with gr.Accordion("🔐 Model Settings", open=False):
|
| 171 |
-
ollama_url = gr.Textbox(
|
| 172 |
-
label="Ollama URL (required for Mistral)",
|
| 173 |
-
placeholder="http://localhost:11434",
|
| 174 |
-
visible=True
|
| 175 |
-
)
|
| 176 |
-
|
| 177 |
-
gemini_api_key = gr.Textbox(
|
| 178 |
-
label="Gemini API Key (required for Gemini)",
|
| 179 |
-
placeholder="your-api-key-here",
|
| 180 |
-
visible=False,
|
| 181 |
-
type="password"
|
| 182 |
-
)
|
| 183 |
-
|
| 184 |
-
status_output = gr.Textbox(
|
| 185 |
-
label="Status",
|
| 186 |
-
interactive=False,
|
| 187 |
-
elem_classes="prose"
|
| 188 |
-
)
|
| 189 |
-
|
| 190 |
-
gr.Markdown("""
|
| 191 |
-
**Instructions:**
|
| 192 |
-
1. Enter a website URL
|
| 193 |
-
2. Select your preferred model
|
| 194 |
-
3. Configure model settings if needed
|
| 195 |
-
4. Click 'Index Website'
|
| 196 |
-
""")
|
| 197 |
-
|
| 198 |
-
with gr.TabItem("💬 Chat"):
|
| 199 |
-
with gr.Row():
|
| 200 |
-
with gr.Column(scale=2):
|
| 201 |
-
# New session ID input for resuming sessions
|
| 202 |
-
with gr.Accordion("🔍 Resume Previous Session", open=False):
|
| 203 |
-
existing_session_input = gr.Textbox(
|
| 204 |
-
label="Enter existing Session ID",
|
| 205 |
-
placeholder="Paste your session ID here...",
|
| 206 |
-
interactive=True
|
| 207 |
-
)
|
| 208 |
-
load_session_btn = gr.Button(
|
| 209 |
-
"🔁 Load Session",
|
| 210 |
-
variant="secondary"
|
| 211 |
-
)
|
| 212 |
-
session_status = gr.Textbox(
|
| 213 |
-
label="Session Status",
|
| 214 |
-
interactive=False
|
| 215 |
-
)
|
| 216 |
-
|
| 217 |
-
chatbot = gr.Chatbot(
|
| 218 |
-
label="Chat History",
|
| 219 |
-
height=500,
|
| 220 |
-
avatar_images=(None, None),
|
| 221 |
-
show_copy_button=True,
|
| 222 |
-
type="messages" # Use OpenAI-style messages
|
| 223 |
-
)
|
| 224 |
-
|
| 225 |
-
with gr.Row():
|
| 226 |
-
message_input = gr.Textbox(
|
| 227 |
-
label="Type your message",
|
| 228 |
-
placeholder="Ask about the website content...",
|
| 229 |
-
interactive=True,
|
| 230 |
-
container=False,
|
| 231 |
-
scale=7,
|
| 232 |
-
autofocus=True
|
| 233 |
-
)
|
| 234 |
-
|
| 235 |
-
send_btn = gr.Button(
|
| 236 |
-
"Send",
|
| 237 |
-
variant="primary",
|
| 238 |
-
scale=1,
|
| 239 |
-
min_width=100
|
| 240 |
-
)
|
| 241 |
-
|
| 242 |
-
# Event handlers
|
| 243 |
-
model_choice.change(
|
| 244 |
-
fn=toggle_model_inputs,
|
| 245 |
-
inputs=model_choice,
|
| 246 |
-
outputs=[ollama_url, gemini_api_key]
|
| 247 |
-
)
|
| 248 |
-
|
| 249 |
-
index_btn.click(
|
| 250 |
-
fn=create_session,
|
| 251 |
-
outputs=session_id
|
| 252 |
-
).success(
|
| 253 |
-
fn=index_website,
|
| 254 |
-
inputs=[url_input, session_id],
|
| 255 |
-
outputs=[status_output]
|
| 256 |
-
)
|
| 257 |
-
|
| 258 |
-
# New handler for loading existing sessions
|
| 259 |
-
load_session_btn.click(
|
| 260 |
-
fn=load_session,
|
| 261 |
-
inputs=[existing_session_input],
|
| 262 |
-
outputs=[session_id, session_status]
|
| 263 |
-
)
|
| 264 |
-
|
| 265 |
-
send_btn.click(
|
| 266 |
-
fn=chat_response,
|
| 267 |
-
inputs=[session_id, message_input, model_choice, ollama_url, gemini_api_key, chatbot],
|
| 268 |
-
outputs=[chatbot, message_input]
|
| 269 |
-
)
|
| 270 |
-
|
| 271 |
-
# Allow submitting with Enter key
|
| 272 |
-
message_input.submit(
|
| 273 |
-
fn=chat_response,
|
| 274 |
-
inputs=[session_id, message_input, model_choice, ollama_url, gemini_api_key, chatbot],
|
| 275 |
-
outputs=[chatbot, message_input]
|
| 276 |
-
)
|
| 277 |
-
|
| 278 |
-
if __name__ == "__main__":
|
| 279 |
-
demo.launch(
|
| 280 |
-
server_name="0.0.0.0",
|
| 281 |
-
server_port=7860,
|
| 282 |
-
favicon_path="assets/favicon.ico" # Local path, not URL
|
| 283 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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