SVashishta1
commited on
Commit
·
8207117
1
Parent(s):
7192613
Your commit message
Browse files
.DS_Store
CHANGED
|
Binary files a/.DS_Store and b/.DS_Store differ
|
|
|
app.py
CHANGED
|
@@ -1,28 +1,105 @@
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import gradio as gr
|
| 4 |
-
from dotenv import load_dotenv
|
| 5 |
import tempfile
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
def process_text_query(query, history):
|
| 20 |
"""Process a text query and update chat history"""
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
response =
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
# Update history
|
| 28 |
history.append((query, response))
|
|
@@ -30,50 +107,84 @@ def process_text_query(query, history):
|
|
| 30 |
|
| 31 |
def process_file_upload(files):
|
| 32 |
"""Process uploaded files and index them"""
|
| 33 |
-
if not files:
|
| 34 |
-
return "No files uploaded"
|
| 35 |
-
|
| 36 |
file_info = []
|
| 37 |
for file in files:
|
| 38 |
file_path = file.name
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
return "\n".join(file_info)
|
| 46 |
|
| 47 |
-
def
|
| 48 |
-
"""
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
return "No documents indexed yet"
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
# Create Gradio interface
|
| 60 |
-
with gr.Blocks(title="Document Assistant") as demo:
|
| 61 |
-
gr.Markdown("#
|
| 62 |
-
gr.Markdown("Upload documents
|
| 63 |
|
| 64 |
with gr.Tab("Chat"):
|
| 65 |
chatbot = gr.Chatbot(height=400)
|
| 66 |
|
| 67 |
with gr.Row():
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
with gr.Row():
|
| 74 |
submit_btn = gr.Button("Submit")
|
| 75 |
clear_btn = gr.Button("Clear")
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
# Event handlers
|
| 78 |
submit_btn.click(
|
| 79 |
process_text_query,
|
|
@@ -88,6 +199,26 @@ with gr.Blocks(title="Document Assistant") as demo:
|
|
| 88 |
)
|
| 89 |
|
| 90 |
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
with gr.Tab("Document Upload"):
|
| 93 |
file_upload = gr.File(
|
|
@@ -103,23 +234,13 @@ with gr.Blocks(title="Document Assistant") as demo:
|
|
| 103 |
inputs=[file_upload],
|
| 104 |
outputs=[upload_output]
|
| 105 |
)
|
| 106 |
-
|
| 107 |
-
list_docs_button = gr.Button("List Indexed Documents")
|
| 108 |
-
docs_output = gr.Textbox(label="Indexed Documents")
|
| 109 |
-
|
| 110 |
-
list_docs_button.click(
|
| 111 |
-
list_documents,
|
| 112 |
-
inputs=[],
|
| 113 |
-
outputs=[docs_output]
|
| 114 |
-
)
|
| 115 |
|
| 116 |
with gr.Tab("Settings"):
|
| 117 |
gr.Markdown("## System Settings")
|
| 118 |
api_key = gr.Textbox(
|
| 119 |
label="Groq API Key",
|
| 120 |
placeholder="Enter your Groq API key",
|
| 121 |
-
type="password"
|
| 122 |
-
value=os.getenv("GROQ_API_KEY", "")
|
| 123 |
)
|
| 124 |
save_btn = gr.Button("Save Settings")
|
| 125 |
|
|
@@ -133,5 +254,37 @@ with gr.Blocks(title="Document Assistant") as demo:
|
|
| 133 |
outputs=[gr.Textbox(label="Status")]
|
| 134 |
)
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import gradio as gr
|
|
|
|
| 4 |
import tempfile
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import sqlite3
|
| 7 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 8 |
+
#test
|
| 9 |
+
# Add parent directory to path to import backend modules
|
| 10 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 11 |
|
| 12 |
+
from backend.main import process_query, upload_document, process_voice
|
| 13 |
+
from backend.db import SQLiteDB
|
| 14 |
+
from backend.vector_db import ChromaVectorDB
|
| 15 |
+
from backend.query_engine import QueryEngine
|
| 16 |
+
from backend.voice_assist import VoiceAssistant
|
| 17 |
+
from backend.document_parser import DocumentParser
|
| 18 |
+
from backend.agents import DocumentAgents
|
| 19 |
|
| 20 |
+
# Initialize components
|
| 21 |
+
sqlite_db = SQLiteDB()
|
| 22 |
+
vector_db = ChromaVectorDB(os.getenv("CHROMA_DB_PATH", "./data/chroma_db"))
|
| 23 |
+
query_engine = QueryEngine()
|
| 24 |
+
voice_assistant = VoiceAssistant()
|
| 25 |
|
| 26 |
+
# Initialize the document parser and agents
|
| 27 |
+
document_parser = DocumentParser()
|
| 28 |
+
document_agents = DocumentAgents()
|
| 29 |
|
| 30 |
+
# Define the prompt with examples
|
| 31 |
+
query_prompt = ChatPromptTemplate.from_messages(
|
| 32 |
+
[
|
| 33 |
+
("system", """
|
| 34 |
+
You are an SQL and data analysis expert. Generate an appropriate SQL query using SQLite syntax for the question provided, without any explanations or code comments.
|
| 35 |
+
Follow SQLite-specific conventions, as shown in the examples below:
|
| 36 |
+
|
| 37 |
+
Example 1:
|
| 38 |
+
Question: "What is the average fare for trips over 10 miles?"
|
| 39 |
+
SQL Query: SELECT AVG(fare_amount) FROM taxi_data WHERE trip_distance > 10;
|
| 40 |
+
|
| 41 |
+
Example 2:
|
| 42 |
+
Question: "How many trips were taken in each month?"
|
| 43 |
+
SQL Query: SELECT strftime('%m', pickup_datetime) AS month, COUNT(*) AS trip_count FROM taxi_data GROUP BY month;
|
| 44 |
+
|
| 45 |
+
Example 3:
|
| 46 |
+
Question: "What is the total fare amount for each driver (medallion) per day?"
|
| 47 |
+
SQL Query: SELECT DATE(pickup_datetime) AS date, medallion, SUM(fare_amount) AS total_fare FROM taxi_data GROUP BY date, medallion;
|
| 48 |
+
|
| 49 |
+
SQLite-Specific Conventions:
|
| 50 |
+
|
| 51 |
+
1. Date and Time Extraction:
|
| 52 |
+
- Instead of `EXTRACT(YEAR FROM column)`, use `strftime('%Y', column)` to extract the year.
|
| 53 |
+
- Example: `SELECT strftime('%Y', pickup_datetime) FROM taxi_data;`
|
| 54 |
+
|
| 55 |
+
2. String Length:
|
| 56 |
+
- Instead of `CHAR_LENGTH(column)`, use `LENGTH(column)`.
|
| 57 |
+
- Example: `SELECT LENGTH(passenger_name) FROM taxi_data;`
|
| 58 |
+
|
| 59 |
+
3. Regular Expressions:
|
| 60 |
+
- SQLite does not support `REGEXP`. Use `LIKE` for simple patterns or avoid regular expressions.
|
| 61 |
+
- Example: `SELECT * FROM taxi_data WHERE passenger_name LIKE 'A%';`
|
| 62 |
+
|
| 63 |
+
4. Window Functions:
|
| 64 |
+
- For row numbering, use `ROW_NUMBER()` if supported, or simulate with joins.
|
| 65 |
+
- Example: `SELECT id, ROW_NUMBER() OVER (ORDER BY pickup_datetime) AS row_num FROM taxi_data;`
|
| 66 |
+
|
| 67 |
+
5. Data Type Casting:
|
| 68 |
+
- Use `CAST(column AS TYPE)`, but note that SQLite supports limited types.
|
| 69 |
+
- Example: `SELECT CAST(fare_amount AS INTEGER) FROM taxi_data;`
|
| 70 |
+
|
| 71 |
+
6. Full Outer Join Workaround:
|
| 72 |
+
- SQLite doesn't support `FULL OUTER JOIN`. Combine `LEFT JOIN` and `UNION` for a similar effect.
|
| 73 |
+
- Example:
|
| 74 |
+
```
|
| 75 |
+
SELECT a.*, b.*
|
| 76 |
+
FROM table_a a
|
| 77 |
+
LEFT JOIN table_b b ON a.id = b.id
|
| 78 |
+
UNION
|
| 79 |
+
SELECT a.*, b.*
|
| 80 |
+
FROM table_a a
|
| 81 |
+
RIGHT JOIN table_b b ON a.id = b.id;
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Use these examples and guidelines to generate an SQL query compatible with SQLite syntax for the question provided.
|
| 85 |
+
"""),
|
| 86 |
+
("human", "{question}"),
|
| 87 |
+
]
|
| 88 |
+
)
|
| 89 |
|
| 90 |
def process_text_query(query, history):
|
| 91 |
"""Process a text query and update chat history"""
|
| 92 |
+
# Log query to database
|
| 93 |
+
sqlite_db.log_query(query)
|
| 94 |
+
|
| 95 |
+
# Get relevant documents
|
| 96 |
+
relevant_docs = vector_db.search(query)
|
| 97 |
|
| 98 |
+
# Generate response
|
| 99 |
+
response = query_engine.generate_response(query, relevant_docs)
|
| 100 |
+
|
| 101 |
+
# Update database with response
|
| 102 |
+
sqlite_db.log_query(query, response)
|
| 103 |
|
| 104 |
# Update history
|
| 105 |
history.append((query, response))
|
|
|
|
| 107 |
|
| 108 |
def process_file_upload(files):
|
| 109 |
"""Process uploaded files and index them"""
|
|
|
|
|
|
|
|
|
|
| 110 |
file_info = []
|
| 111 |
for file in files:
|
| 112 |
file_path = file.name
|
| 113 |
+
file_name = os.path.basename(file_path)
|
| 114 |
+
file_type = os.path.splitext(file_name)[1].lower()
|
| 115 |
|
| 116 |
+
# Parse document
|
| 117 |
+
text_chunks = document_parser.parse_document(file_path)
|
| 118 |
|
| 119 |
+
# Add to SQLite DB
|
| 120 |
+
doc_id = sqlite_db.add_document(file_name, file_path, file_type)
|
| 121 |
+
|
| 122 |
+
# Add to vector DB
|
| 123 |
+
vector_db.add_document(file_path, text_chunks, {"doc_id": doc_id})
|
| 124 |
+
|
| 125 |
+
file_info.append(f"Indexed: {file_name} ({len(text_chunks)} chunks)")
|
| 126 |
|
| 127 |
return "\n".join(file_info)
|
| 128 |
|
| 129 |
+
def process_voice_input(audio_path):
|
| 130 |
+
"""Process voice input and return transcribed text"""
|
| 131 |
+
if audio_path is None:
|
| 132 |
+
return "No audio recorded"
|
|
|
|
| 133 |
|
| 134 |
+
# Transcribe audio
|
| 135 |
+
text = voice_assistant.speech_to_text(audio_path)
|
| 136 |
+
return text
|
| 137 |
+
|
| 138 |
+
def text_to_speech_output(text):
|
| 139 |
+
"""Convert text to speech"""
|
| 140 |
+
if not text:
|
| 141 |
+
return None
|
| 142 |
|
| 143 |
+
audio_path = voice_assistant.text_to_speech(text)
|
| 144 |
+
return audio_path
|
| 145 |
+
|
| 146 |
+
def load_csv_to_sqlite(file_path, conn):
|
| 147 |
+
# Read the CSV in chunks
|
| 148 |
+
chunksize = 1000 # Adjust based on your memory constraints
|
| 149 |
+
for chunk in pd.read_csv(file_path, chunksize=chunksize):
|
| 150 |
+
# Perform any necessary data cleaning on the chunk
|
| 151 |
+
if 'pickup_datetime' in chunk.columns:
|
| 152 |
+
chunk['pickup_datetime'] = pd.to_datetime(chunk['pickup_datetime'], errors='coerce')
|
| 153 |
+
chunk = chunk.dropna(subset=['pickup_datetime'])
|
| 154 |
+
|
| 155 |
+
# Load the chunk into the SQLite database
|
| 156 |
+
chunk.to_sql('data_tab', conn, if_exists='append', index=False, method='multi')
|
| 157 |
|
| 158 |
# Create Gradio interface
|
| 159 |
+
with gr.Blocks(title="AI Document Analysis & Voice Assistant") as demo:
|
| 160 |
+
gr.Markdown("# 🤖 AI Document Analysis & Voice Assistant")
|
| 161 |
+
gr.Markdown("Upload documents, ask questions, and get voice responses!")
|
| 162 |
|
| 163 |
with gr.Tab("Chat"):
|
| 164 |
chatbot = gr.Chatbot(height=400)
|
| 165 |
|
| 166 |
with gr.Row():
|
| 167 |
+
with gr.Column(scale=8):
|
| 168 |
+
msg = gr.Textbox(
|
| 169 |
+
placeholder="Ask a question about your documents...",
|
| 170 |
+
show_label=False
|
| 171 |
+
)
|
| 172 |
+
with gr.Column(scale=1):
|
| 173 |
+
voice_btn = gr.Button("🎤")
|
| 174 |
|
| 175 |
with gr.Row():
|
| 176 |
submit_btn = gr.Button("Submit")
|
| 177 |
clear_btn = gr.Button("Clear")
|
| 178 |
|
| 179 |
+
audio_output = gr.Audio(label="Voice Response", type="filepath")
|
| 180 |
+
|
| 181 |
+
# Voice input
|
| 182 |
+
voice_input = gr.Audio(
|
| 183 |
+
label="Voice Input",
|
| 184 |
+
type="filepath",
|
| 185 |
+
visible=False
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
# Event handlers
|
| 189 |
submit_btn.click(
|
| 190 |
process_text_query,
|
|
|
|
| 199 |
)
|
| 200 |
|
| 201 |
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
| 202 |
+
|
| 203 |
+
voice_btn.click(
|
| 204 |
+
lambda: gr.update(visible=True),
|
| 205 |
+
None,
|
| 206 |
+
voice_input
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
voice_input.change(
|
| 210 |
+
process_voice_input,
|
| 211 |
+
inputs=[voice_input],
|
| 212 |
+
outputs=[msg]
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
# Add TTS functionality
|
| 216 |
+
tts_btn = gr.Button("🔊 Speak Response")
|
| 217 |
+
tts_btn.click(
|
| 218 |
+
text_to_speech_output,
|
| 219 |
+
inputs=[chatbot],
|
| 220 |
+
outputs=[audio_output]
|
| 221 |
+
)
|
| 222 |
|
| 223 |
with gr.Tab("Document Upload"):
|
| 224 |
file_upload = gr.File(
|
|
|
|
| 234 |
inputs=[file_upload],
|
| 235 |
outputs=[upload_output]
|
| 236 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
with gr.Tab("Settings"):
|
| 239 |
gr.Markdown("## System Settings")
|
| 240 |
api_key = gr.Textbox(
|
| 241 |
label="Groq API Key",
|
| 242 |
placeholder="Enter your Groq API key",
|
| 243 |
+
type="password"
|
|
|
|
| 244 |
)
|
| 245 |
save_btn = gr.Button("Save Settings")
|
| 246 |
|
|
|
|
| 254 |
outputs=[gr.Textbox(label="Status")]
|
| 255 |
)
|
| 256 |
|
| 257 |
+
with gr.Tab("Advanced Query"):
|
| 258 |
+
gr.Markdown("# 🧠 Complex Query Processing")
|
| 259 |
+
gr.Markdown("Use AI agents to process complex queries about your documents")
|
| 260 |
+
|
| 261 |
+
complex_chatbot = gr.Chatbot(height=400)
|
| 262 |
+
|
| 263 |
+
with gr.Row():
|
| 264 |
+
complex_msg = gr.Textbox(
|
| 265 |
+
placeholder="Ask a complex question requiring analysis...",
|
| 266 |
+
show_label=False
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
with gr.Row():
|
| 270 |
+
complex_submit_btn = gr.Button("Process with Agents")
|
| 271 |
+
complex_clear_btn = gr.Button("Clear")
|
| 272 |
+
|
| 273 |
+
# Event handlers
|
| 274 |
+
complex_submit_btn.click(
|
| 275 |
+
process_complex_query,
|
| 276 |
+
inputs=[complex_msg, complex_chatbot],
|
| 277 |
+
outputs=[complex_msg, complex_chatbot]
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
complex_msg.submit(
|
| 281 |
+
process_complex_query,
|
| 282 |
+
inputs=[complex_msg, complex_chatbot],
|
| 283 |
+
outputs=[complex_msg, complex_chatbot]
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
complex_clear_btn.click(lambda: None, None, complex_chatbot, queue=False)
|
| 287 |
+
|
| 288 |
+
# Launch the app
|
| 289 |
+
if __name__ == "__main__":
|
| 290 |
+
demo.launch()
|