SVashishta1
commited on
Commit
Β·
36118e8
1
Parent(s):
42d8891
Update: Added visualization tab and improved UI
Browse files- .DS_Store +0 -0
- README.md +57 -21
- app.py +185 -143
- huggingface.yml +5 -4
- requirements.txt +7 -6
.DS_Store
CHANGED
|
Binary files a/.DS_Store and b/.DS_Store differ
|
|
|
README.md
CHANGED
|
@@ -1,38 +1,74 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
| 10 |
license: mit
|
| 11 |
-
|
|
|
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
This is an AI-powered document analysis chatbot that allows you to:
|
| 19 |
-
|
| 20 |
-
- Upload documents (PDF, TXT, DOCX, CSV, XLSX)
|
| 21 |
-
- Ask questions about your documents
|
| 22 |
-
- Get AI-generated responses based on document content
|
| 23 |
|
| 24 |
## Features
|
| 25 |
|
| 26 |
-
- **Document
|
| 27 |
-
- **
|
| 28 |
-
- **
|
| 29 |
-
- **
|
|
|
|
| 30 |
|
| 31 |
## How to Use
|
| 32 |
|
| 33 |
-
1. **Upload Documents**:
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
## Technical Details
|
| 38 |
|
|
|
|
| 1 |
---
|
| 2 |
+
title: "LLM Powered Database Chatbot"
|
| 3 |
+
emoji: "π€"
|
| 4 |
+
colorFrom: "blue"
|
| 5 |
+
colorTo: "purple"
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 4.19.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
space: Vashishta-S-2141/LLM_Powered_Database_Chatbot
|
| 11 |
license: mit
|
| 12 |
+
hardware: cpu
|
| 13 |
+
persistentStorage: true
|
| 14 |
---
|
| 15 |
|
| 16 |
+
# π€ LLM Powered Database Chatbot
|
| 17 |
|
| 18 |
+
A powerful chatbot that can analyze your documents and data, providing insights and visualizations through natural language queries.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
## Features
|
| 21 |
|
| 22 |
+
- **Document Analysis**: Upload and query PDFs, TXT, DOCX, CSV, and XLSX files
|
| 23 |
+
- **Data Visualization**: Generate interactive plots and charts from your data
|
| 24 |
+
- **Natural Language Interface**: Ask questions in plain English
|
| 25 |
+
- **Multiple Data Sources**: Work with both documents and structured data
|
| 26 |
+
- **Interactive Visualizations**: View and save your data visualizations
|
| 27 |
|
| 28 |
## How to Use
|
| 29 |
|
| 30 |
+
1. **Upload Documents**:
|
| 31 |
+
- Go to the "Document Upload" tab
|
| 32 |
+
- Upload your files (PDF, TXT, DOCX, CSV, or XLSX)
|
| 33 |
+
- Click "Process & Index Documents"
|
| 34 |
+
|
| 35 |
+
2. **Ask Questions**:
|
| 36 |
+
- Type your question in the chat interface
|
| 37 |
+
- The bot will analyze your documents and provide answers
|
| 38 |
+
- For data-related questions, it will generate visualizations
|
| 39 |
+
|
| 40 |
+
3. **View Visualizations**:
|
| 41 |
+
- Switch to the "Visualizations" tab to see your plots
|
| 42 |
+
- Use the buttons to save or clear visualizations
|
| 43 |
+
|
| 44 |
+
## Requirements
|
| 45 |
+
|
| 46 |
+
- Groq API key (set in environment variables)
|
| 47 |
+
- Python 3.8 or higher
|
| 48 |
+
|
| 49 |
+
## Local Development
|
| 50 |
+
|
| 51 |
+
1. Clone this repository
|
| 52 |
+
2. Install dependencies:
|
| 53 |
+
```bash
|
| 54 |
+
pip install -r requirements.txt
|
| 55 |
+
```
|
| 56 |
+
3. Set up environment variables:
|
| 57 |
+
```bash
|
| 58 |
+
export GROQ_API_KEY=your_api_key_here
|
| 59 |
+
```
|
| 60 |
+
4. Run the application:
|
| 61 |
+
```bash
|
| 62 |
+
python app.py
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
## License
|
| 66 |
+
|
| 67 |
+
MIT License
|
| 68 |
+
|
| 69 |
+
## Author
|
| 70 |
+
|
| 71 |
+
Vashishta-S-2141
|
| 72 |
|
| 73 |
## Technical Details
|
| 74 |
|
app.py
CHANGED
|
@@ -6,7 +6,7 @@ import tempfile
|
|
| 6 |
import pandas as pd
|
| 7 |
import sqlite3
|
| 8 |
from langchain_core.prompts import ChatPromptTemplate
|
| 9 |
-
from
|
| 10 |
import plotly.express as px
|
| 11 |
import time
|
| 12 |
import plotly.io as pio
|
|
@@ -45,6 +45,17 @@ llm = ChatGroq(
|
|
| 45 |
DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "csv_data.db")
|
| 46 |
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
# Current context to track what we're working with
|
| 49 |
current_context = {
|
| 50 |
"file_type": None,
|
|
@@ -248,98 +259,53 @@ def process_text_query(query, history):
|
|
| 248 |
cols_str = ", ".join(cols_to_use)
|
| 249 |
sql_query = f"SELECT {cols_str} FROM data_tab WHERE {numeric_cols[0]} IS NOT NULL LIMIT 1000;"
|
| 250 |
else:
|
| 251 |
-
# Not enough numeric columns
|
| 252 |
sql_query = "SELECT * FROM data_tab LIMIT 10;"
|
| 253 |
else:
|
| 254 |
-
#
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
# Clean the SQL query
|
| 259 |
-
sql_query = clean_sql_query(raw_sql_query)
|
| 260 |
|
| 261 |
-
|
|
|
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
result_df = pd.read_sql_query(sql_query, conn)
|
| 266 |
-
|
| 267 |
-
# Generate data summary
|
| 268 |
-
if not result_df.empty:
|
| 269 |
-
data_summary = result_df.describe(include='all').to_string()
|
| 270 |
-
|
| 271 |
-
# For small result sets, include the actual data
|
| 272 |
-
if len(result_df) <= 10:
|
| 273 |
-
data_summary += f"\n\nFull Results:\n{result_df.to_string()}"
|
| 274 |
-
else:
|
| 275 |
-
data_summary += f"\n\nFirst 5 rows:\n{result_df.head(5).to_string()}"
|
| 276 |
-
else:
|
| 277 |
-
data_summary = "No relevant data found."
|
| 278 |
-
|
| 279 |
-
# Generate interpretation
|
| 280 |
-
answer_chain = interpret_prompt | llm
|
| 281 |
-
interpretation = answer_chain.invoke({
|
| 282 |
-
"question": query,
|
| 283 |
-
"sql_query": sql_query,
|
| 284 |
-
"data_summary": data_summary
|
| 285 |
-
}).content.strip()
|
| 286 |
-
|
| 287 |
-
# Create the response
|
| 288 |
-
response = f"**SQL Query:**\n```sql\n{sql_query}\n```\n\n"
|
| 289 |
-
|
| 290 |
-
if not result_df.empty:
|
| 291 |
-
if len(result_df) > 10:
|
| 292 |
-
response += f"**Results (first 5 of {len(result_df)} rows):**\n```\n{result_df.head(5).to_string()}\n```\n\n"
|
| 293 |
-
else:
|
| 294 |
-
response += f"**Results:**\n```\n{result_df.to_string()}\n```\n\n"
|
| 295 |
-
else:
|
| 296 |
-
response += "**No results found.**\n\n"
|
| 297 |
-
|
| 298 |
-
response += f"**Analysis:**\n{interpretation}"
|
| 299 |
-
|
| 300 |
-
# Add visualization if requested
|
| 301 |
-
if is_visualization and not result_df.empty:
|
| 302 |
-
try:
|
| 303 |
-
# Generate visualization
|
| 304 |
-
viz_html = generate_visualization(result_df, query)
|
| 305 |
-
|
| 306 |
-
if viz_html:
|
| 307 |
-
# Add the visualization to the response
|
| 308 |
-
response += f"\n\n{viz_html}"
|
| 309 |
-
|
| 310 |
-
# Add note about visualization
|
| 311 |
-
response += "\n\n**A visualization has been generated and is displayed above.**"
|
| 312 |
-
else:
|
| 313 |
-
response += "\n\n**Could not generate visualization due to an error.**"
|
| 314 |
-
|
| 315 |
-
except Exception as viz_error:
|
| 316 |
-
print(f"Visualization error: {str(viz_error)}")
|
| 317 |
-
import traceback
|
| 318 |
-
traceback.print_exc()
|
| 319 |
|
| 320 |
-
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
|
| 323 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
except Exception as e:
|
| 326 |
-
|
|
|
|
|
|
|
| 327 |
|
| 328 |
else:
|
| 329 |
-
#
|
| 330 |
try:
|
| 331 |
response = document_assistant.process_query(query)
|
|
|
|
|
|
|
| 332 |
except Exception as e:
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
processing_time = time.time() - start_time
|
| 337 |
-
response += f"\n\n(Query processed in {processing_time:.2f} seconds)"
|
| 338 |
-
|
| 339 |
-
# Add the response to history
|
| 340 |
-
history.append({"role": "assistant", "content": response})
|
| 341 |
-
|
| 342 |
-
return "", history
|
| 343 |
|
| 344 |
def process_file_upload(files):
|
| 345 |
"""Process uploaded files and index them"""
|
|
@@ -638,8 +604,8 @@ def generate_visualization(result_df, query):
|
|
| 638 |
print("Visualization requested, attempting to create plot...")
|
| 639 |
|
| 640 |
# Set common figure parameters
|
| 641 |
-
fig_width =
|
| 642 |
-
fig_height = 800 #
|
| 643 |
|
| 644 |
# Determine visualization type from query
|
| 645 |
viz_type = 'bar' # Default
|
|
@@ -749,17 +715,13 @@ def generate_visualization(result_df, query):
|
|
| 749 |
result_df,
|
| 750 |
x=x_col,
|
| 751 |
y=y_col,
|
| 752 |
-
title=f'Bar Chart of {y_col} by {x_col}'
|
| 753 |
-
width=900,
|
| 754 |
-
height=800
|
| 755 |
)
|
| 756 |
else:
|
| 757 |
fig = px.bar(
|
| 758 |
result_df,
|
| 759 |
x=x_col,
|
| 760 |
-
title=f'Bar Chart of {x_col}'
|
| 761 |
-
width=900,
|
| 762 |
-
height=800
|
| 763 |
)
|
| 764 |
|
| 765 |
# Improve bar chart layout
|
|
@@ -777,14 +739,25 @@ def generate_visualization(result_df, query):
|
|
| 777 |
margin=dict(l=40, r=40, t=80, b=80, pad=4), # Balanced margins
|
| 778 |
autosize=True, # Allow the plot to resize with the container
|
| 779 |
plot_bgcolor='rgba(240,240,240,0.2)', # Light gray background
|
| 780 |
-
paper_bgcolor='white'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 781 |
)
|
| 782 |
|
| 783 |
print(f"Created figure with width={fig_width}, height={fig_height}")
|
| 784 |
|
| 785 |
-
# Convert to image
|
| 786 |
print("Converting figure to image...")
|
| 787 |
-
img_bytes = pio.to_image(fig, format="png", width=fig_width, height=fig_height, scale=
|
| 788 |
print("Image conversion successful")
|
| 789 |
|
| 790 |
# Encode as base64
|
|
@@ -794,8 +767,14 @@ def generate_visualization(result_df, query):
|
|
| 794 |
|
| 795 |
print("HTML conversion successful")
|
| 796 |
|
| 797 |
-
# Return the HTML img tag
|
| 798 |
-
return f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 799 |
|
| 800 |
except Exception as e:
|
| 801 |
import traceback
|
|
@@ -808,6 +787,9 @@ with gr.Blocks(title="LLM Powered Database Chatbot") as demo:
|
|
| 808 |
gr.Markdown("# π€ LLM Powered Database Chatbot")
|
| 809 |
gr.Markdown("Upload documents, ask questions, and get AI-powered responses!")
|
| 810 |
|
|
|
|
|
|
|
|
|
|
| 811 |
with gr.Tab("Chat"):
|
| 812 |
# Use a custom CSS to ensure images are displayed properly
|
| 813 |
gr.HTML("""
|
|
@@ -839,70 +821,124 @@ with gr.Blocks(title="LLM Powered Database Chatbot") as demo:
|
|
| 839 |
show_label=False
|
| 840 |
)
|
| 841 |
with gr.Column(scale=1):
|
| 842 |
-
|
| 843 |
-
# voice_btn = gr.Button("π€")
|
| 844 |
-
pass # I am using pass so the code still works
|
| 845 |
|
| 846 |
with gr.Row():
|
| 847 |
submit_btn = gr.Button("Submit")
|
| 848 |
clear_btn = gr.Button("Clear")
|
| 849 |
clear_context_btn = gr.Button("Clear Context")
|
|
|
|
|
|
|
|
|
|
| 850 |
|
| 851 |
-
|
| 852 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 853 |
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
)
|
| 861 |
-
"""
|
| 862 |
|
| 863 |
-
#
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 869 |
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
inputs=[msg, chatbot],
|
| 873 |
-
outputs=[msg, chatbot]
|
| 874 |
-
)
|
| 875 |
|
| 876 |
-
|
| 877 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 878 |
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
lambda: gr.update(visible=True),
|
| 883 |
-
None,
|
| 884 |
-
voice_input
|
| 885 |
)
|
| 886 |
-
"""
|
| 887 |
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
inputs=[voice_input],
|
| 893 |
-
outputs=[msg]
|
| 894 |
)
|
| 895 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 896 |
|
| 897 |
-
#
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 906 |
|
| 907 |
with gr.Tab("Document Upload"):
|
| 908 |
file_upload = gr.File(
|
|
@@ -985,4 +1021,10 @@ with gr.Blocks(title="LLM Powered Database Chatbot") as demo:
|
|
| 985 |
|
| 986 |
# Launch the app
|
| 987 |
if __name__ == "__main__":
|
| 988 |
-
demo.launch(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import pandas as pd
|
| 7 |
import sqlite3
|
| 8 |
from langchain_core.prompts import ChatPromptTemplate
|
| 9 |
+
from langchain_community.chat_models import ChatGroq
|
| 10 |
import plotly.express as px
|
| 11 |
import time
|
| 12 |
import plotly.io as pio
|
|
|
|
| 45 |
DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "csv_data.db")
|
| 46 |
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
| 47 |
|
| 48 |
+
# Create data directory if it doesn't exist
|
| 49 |
+
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
|
| 50 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 51 |
+
|
| 52 |
+
# Create chroma_db directory if it doesn't exist
|
| 53 |
+
CHROMA_DB_DIR = os.path.join(DATA_DIR, "chroma_db")
|
| 54 |
+
os.makedirs(CHROMA_DB_DIR, exist_ok=True)
|
| 55 |
+
|
| 56 |
+
# Set environment variables for ChromaDB
|
| 57 |
+
os.environ["CHROMA_DB_PATH"] = CHROMA_DB_DIR
|
| 58 |
+
|
| 59 |
# Current context to track what we're working with
|
| 60 |
current_context = {
|
| 61 |
"file_type": None,
|
|
|
|
| 259 |
cols_str = ", ".join(cols_to_use)
|
| 260 |
sql_query = f"SELECT {cols_str} FROM data_tab WHERE {numeric_cols[0]} IS NOT NULL LIMIT 1000;"
|
| 261 |
else:
|
|
|
|
| 262 |
sql_query = "SELECT * FROM data_tab LIMIT 10;"
|
| 263 |
else:
|
| 264 |
+
# For other queries, use the LLM to generate SQL
|
| 265 |
+
sql_query = llm.invoke(query_prompt.format(question=question_with_context)).content
|
| 266 |
+
sql_query = clean_sql_query(sql_query)
|
|
|
|
|
|
|
|
|
|
| 267 |
|
| 268 |
+
# Execute the query
|
| 269 |
+
result_df = pd.read_sql_query(sql_query, conn)
|
| 270 |
|
| 271 |
+
# Close the connection
|
| 272 |
+
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
+
# Generate visualization if requested
|
| 275 |
+
if is_visualization:
|
| 276 |
+
viz_html = generate_visualization(result_df, query)
|
| 277 |
+
if viz_html:
|
| 278 |
+
# Add the visualization to history
|
| 279 |
+
history.append({"role": "assistant", "content": viz_html})
|
| 280 |
+
return viz_html, history
|
| 281 |
|
| 282 |
+
# If no visualization or visualization failed, generate text response
|
| 283 |
+
data_summary = result_df.to_string()
|
| 284 |
+
response = llm.invoke(interpret_prompt.format(
|
| 285 |
+
question=query,
|
| 286 |
+
sql_query=sql_query,
|
| 287 |
+
data_summary=data_summary
|
| 288 |
+
)).content
|
| 289 |
+
|
| 290 |
+
# Add the response to history
|
| 291 |
+
history.append({"role": "assistant", "content": response})
|
| 292 |
+
return response, history
|
| 293 |
|
| 294 |
except Exception as e:
|
| 295 |
+
error_msg = f"Error processing query: {str(e)}"
|
| 296 |
+
history.append({"role": "assistant", "content": error_msg})
|
| 297 |
+
return error_msg, history
|
| 298 |
|
| 299 |
else:
|
| 300 |
+
# Handle non-CSV queries (document queries)
|
| 301 |
try:
|
| 302 |
response = document_assistant.process_query(query)
|
| 303 |
+
history.append({"role": "assistant", "content": response})
|
| 304 |
+
return response, history
|
| 305 |
except Exception as e:
|
| 306 |
+
error_msg = f"Error processing query: {str(e)}"
|
| 307 |
+
history.append({"role": "assistant", "content": error_msg})
|
| 308 |
+
return error_msg, history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
|
| 310 |
def process_file_upload(files):
|
| 311 |
"""Process uploaded files and index them"""
|
|
|
|
| 604 |
print("Visualization requested, attempting to create plot...")
|
| 605 |
|
| 606 |
# Set common figure parameters
|
| 607 |
+
fig_width = 1200 # Increased for better quality
|
| 608 |
+
fig_height = 800 # Maintain aspect ratio
|
| 609 |
|
| 610 |
# Determine visualization type from query
|
| 611 |
viz_type = 'bar' # Default
|
|
|
|
| 715 |
result_df,
|
| 716 |
x=x_col,
|
| 717 |
y=y_col,
|
| 718 |
+
title=f'Bar Chart of {y_col} by {x_col}'
|
|
|
|
|
|
|
| 719 |
)
|
| 720 |
else:
|
| 721 |
fig = px.bar(
|
| 722 |
result_df,
|
| 723 |
x=x_col,
|
| 724 |
+
title=f'Bar Chart of {x_col}'
|
|
|
|
|
|
|
| 725 |
)
|
| 726 |
|
| 727 |
# Improve bar chart layout
|
|
|
|
| 739 |
margin=dict(l=40, r=40, t=80, b=80, pad=4), # Balanced margins
|
| 740 |
autosize=True, # Allow the plot to resize with the container
|
| 741 |
plot_bgcolor='rgba(240,240,240,0.2)', # Light gray background
|
| 742 |
+
paper_bgcolor='white',
|
| 743 |
+
font=dict(size=12) # Increase font size
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
# Add hover information
|
| 747 |
+
fig.update_traces(
|
| 748 |
+
hovertemplate="%{x}: %{y}<extra></extra>",
|
| 749 |
+
hoverlabel=dict(
|
| 750 |
+
bgcolor="white",
|
| 751 |
+
font_size=12,
|
| 752 |
+
font_family="Arial"
|
| 753 |
+
)
|
| 754 |
)
|
| 755 |
|
| 756 |
print(f"Created figure with width={fig_width}, height={fig_height}")
|
| 757 |
|
| 758 |
+
# Convert to image with higher quality
|
| 759 |
print("Converting figure to image...")
|
| 760 |
+
img_bytes = pio.to_image(fig, format="png", width=fig_width, height=fig_height, scale=3) # Increased scale for better quality
|
| 761 |
print("Image conversion successful")
|
| 762 |
|
| 763 |
# Encode as base64
|
|
|
|
| 767 |
|
| 768 |
print("HTML conversion successful")
|
| 769 |
|
| 770 |
+
# Return the HTML img tag with responsive sizing
|
| 771 |
+
return f"""
|
| 772 |
+
<div class="visualization-wrapper">
|
| 773 |
+
<img src='{img_src}'
|
| 774 |
+
style='max-width:100%; height:auto; display:block; margin:0 auto;'
|
| 775 |
+
alt='Data Visualization' />
|
| 776 |
+
</div>
|
| 777 |
+
"""
|
| 778 |
|
| 779 |
except Exception as e:
|
| 780 |
import traceback
|
|
|
|
| 787 |
gr.Markdown("# π€ LLM Powered Database Chatbot")
|
| 788 |
gr.Markdown("Upload documents, ask questions, and get AI-powered responses!")
|
| 789 |
|
| 790 |
+
# Add a global variable to store the current visualization
|
| 791 |
+
current_visualization = gr.State(None)
|
| 792 |
+
|
| 793 |
with gr.Tab("Chat"):
|
| 794 |
# Use a custom CSS to ensure images are displayed properly
|
| 795 |
gr.HTML("""
|
|
|
|
| 821 |
show_label=False
|
| 822 |
)
|
| 823 |
with gr.Column(scale=1):
|
| 824 |
+
pass
|
|
|
|
|
|
|
| 825 |
|
| 826 |
with gr.Row():
|
| 827 |
submit_btn = gr.Button("Submit")
|
| 828 |
clear_btn = gr.Button("Clear")
|
| 829 |
clear_context_btn = gr.Button("Clear Context")
|
| 830 |
+
|
| 831 |
+
with gr.Tab("Visualizations"):
|
| 832 |
+
gr.Markdown("## π Data Visualizations")
|
| 833 |
|
| 834 |
+
with gr.Row():
|
| 835 |
+
with gr.Column(scale=3):
|
| 836 |
+
visualization_output = gr.HTML(
|
| 837 |
+
label="Current Visualization",
|
| 838 |
+
elem_classes="visualization-container"
|
| 839 |
+
)
|
| 840 |
+
with gr.Column(scale=1):
|
| 841 |
+
with gr.Group():
|
| 842 |
+
clear_viz_btn = gr.Button("ποΈ Clear Visualization", variant="stop")
|
| 843 |
+
save_viz_btn = gr.Button("πΎ Save Visualization")
|
| 844 |
+
save_status = gr.Textbox(label="Save Status", visible=False)
|
| 845 |
|
| 846 |
+
gr.Markdown("""
|
| 847 |
+
### How to use:
|
| 848 |
+
1. Ask a question about your data in the Chat tab
|
| 849 |
+
2. If your question involves visualization, the plot will appear here
|
| 850 |
+
3. You can switch between Chat and Visualizations tabs to see both the conversation and the plots
|
| 851 |
+
4. Use the buttons above to clear or save the current visualization
|
| 852 |
+
""")
|
|
|
|
| 853 |
|
| 854 |
+
# Add custom CSS for better visualization display
|
| 855 |
+
gr.HTML("""
|
| 856 |
+
<style>
|
| 857 |
+
.visualization-container {
|
| 858 |
+
min-height: 600px;
|
| 859 |
+
max-height: 800px;
|
| 860 |
+
overflow: auto;
|
| 861 |
+
padding: 20px;
|
| 862 |
+
background-color: #f8f9fa;
|
| 863 |
+
border-radius: 8px;
|
| 864 |
+
}
|
| 865 |
+
.visualization-container img {
|
| 866 |
+
max-width: 100%;
|
| 867 |
+
height: auto;
|
| 868 |
+
display: block;
|
| 869 |
+
margin: 0 auto;
|
| 870 |
+
}
|
| 871 |
+
</style>
|
| 872 |
+
""")
|
| 873 |
|
| 874 |
+
def clear_visualization():
|
| 875 |
+
return "", ""
|
|
|
|
|
|
|
|
|
|
| 876 |
|
| 877 |
+
def save_visualization(viz_html):
|
| 878 |
+
if not viz_html:
|
| 879 |
+
return "No visualization to save", gr.update(visible=True)
|
| 880 |
+
|
| 881 |
+
try:
|
| 882 |
+
# Create a unique filename
|
| 883 |
+
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
| 884 |
+
filename = f"visualization_{timestamp}.html"
|
| 885 |
+
filepath = os.path.join(DATA_DIR, filename)
|
| 886 |
+
|
| 887 |
+
# Save the visualization
|
| 888 |
+
with open(filepath, "w") as f:
|
| 889 |
+
f.write(viz_html)
|
| 890 |
+
|
| 891 |
+
return f"Visualization saved as {filename}", gr.update(visible=True)
|
| 892 |
+
except Exception as e:
|
| 893 |
+
return f"Error saving visualization: {str(e)}", gr.update(visible=True)
|
| 894 |
|
| 895 |
+
clear_viz_btn.click(
|
| 896 |
+
clear_visualization,
|
| 897 |
+
outputs=[visualization_output, current_visualization]
|
|
|
|
|
|
|
|
|
|
| 898 |
)
|
|
|
|
| 899 |
|
| 900 |
+
save_viz_btn.click(
|
| 901 |
+
save_visualization,
|
| 902 |
+
inputs=[current_visualization],
|
| 903 |
+
outputs=[save_status, save_status]
|
|
|
|
|
|
|
| 904 |
)
|
| 905 |
+
|
| 906 |
+
# Update the process_text_query function to handle visualizations
|
| 907 |
+
def process_text_query_with_visualization(query, history, current_viz):
|
| 908 |
+
"""Process a text query and update chat history and visualization"""
|
| 909 |
+
if not query:
|
| 910 |
+
return "", history, current_viz
|
| 911 |
|
| 912 |
+
# Process the query and get the response
|
| 913 |
+
response, new_history = process_text_query(query, history)
|
| 914 |
+
|
| 915 |
+
# Check if the response contains a visualization
|
| 916 |
+
if "<img src=" in response:
|
| 917 |
+
# Extract the visualization HTML
|
| 918 |
+
viz_html = response
|
| 919 |
+
# Update the visualization state
|
| 920 |
+
current_viz = viz_html
|
| 921 |
+
# Remove the visualization from the chat response
|
| 922 |
+
response = "I've created a visualization for your query. Please check the 'Visualizations' tab to see it."
|
| 923 |
+
|
| 924 |
+
return response, new_history, current_viz
|
| 925 |
+
|
| 926 |
+
# Update the button click handlers
|
| 927 |
+
submit_btn.click(
|
| 928 |
+
process_text_query_with_visualization,
|
| 929 |
+
inputs=[msg, chatbot, current_visualization],
|
| 930 |
+
outputs=[msg, chatbot, current_visualization]
|
| 931 |
+
).then(
|
| 932 |
+
lambda: None, # Clear the input
|
| 933 |
+
outputs=[msg]
|
| 934 |
+
).then(
|
| 935 |
+
lambda viz: viz if viz else "", # Update visualization tab
|
| 936 |
+
inputs=[current_visualization],
|
| 937 |
+
outputs=[visualization_output]
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
| 941 |
+
clear_context_btn.click(clear_context, None, chatbot, queue=False)
|
| 942 |
|
| 943 |
with gr.Tab("Document Upload"):
|
| 944 |
file_upload = gr.File(
|
|
|
|
| 1021 |
|
| 1022 |
# Launch the app
|
| 1023 |
if __name__ == "__main__":
|
| 1024 |
+
demo.launch(
|
| 1025 |
+
share=True,
|
| 1026 |
+
server_name="0.0.0.0",
|
| 1027 |
+
server_port=7860,
|
| 1028 |
+
show_error=True,
|
| 1029 |
+
debug=True
|
| 1030 |
+
)
|
huggingface.yml
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
-
title:
|
| 2 |
-
emoji:
|
| 3 |
-
colorFrom: blue
|
| 4 |
-
colorTo:
|
| 5 |
sdk: gradio
|
| 6 |
sdk_version: 4.19.0
|
| 7 |
app_file: app.py
|
| 8 |
pinned: false
|
|
|
|
| 9 |
license: mit
|
| 10 |
hardware: cpu
|
| 11 |
persistentStorage: true
|
|
|
|
| 1 |
+
title: "LLM Powered Database Chatbot"
|
| 2 |
+
emoji: "π€"
|
| 3 |
+
colorFrom: "blue"
|
| 4 |
+
colorTo: "purple"
|
| 5 |
sdk: gradio
|
| 6 |
sdk_version: 4.19.0
|
| 7 |
app_file: app.py
|
| 8 |
pinned: false
|
| 9 |
+
space: Vashishta-S-2141/LLM_Powered_Database_Chatbot
|
| 10 |
license: mit
|
| 11 |
hardware: cpu
|
| 12 |
persistentStorage: true
|
requirements.txt
CHANGED
|
@@ -1,4 +1,6 @@
|
|
| 1 |
langchain>=0.1.0
|
|
|
|
|
|
|
| 2 |
groq>=0.4.0
|
| 3 |
chromadb>=0.4.22
|
| 4 |
pymupdf>=1.23.0
|
|
@@ -6,9 +8,8 @@ pandas>=2.0.0
|
|
| 6 |
python-docx>=0.8.11
|
| 7 |
gradio>=4.19.0
|
| 8 |
python-dotenv>=1.0.0
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
kaleido>=0.2.1
|
|
|
|
| 1 |
langchain>=0.1.0
|
| 2 |
+
langchain-core>=0.1.0
|
| 3 |
+
langchain-community>=0.0.10
|
| 4 |
groq>=0.4.0
|
| 5 |
chromadb>=0.4.22
|
| 6 |
pymupdf>=1.23.0
|
|
|
|
| 8 |
python-docx>=0.8.11
|
| 9 |
gradio>=4.19.0
|
| 10 |
python-dotenv>=1.0.0
|
| 11 |
+
plotly>=5.14.0
|
| 12 |
+
kaleido>=0.2.1
|
| 13 |
+
numpy>=1.24.0
|
| 14 |
+
sqlite3>=3.35.0
|
| 15 |
+
python-multipart>=0.0.6
|
|
|