File size: 8,742 Bytes
5dde7f1
 
 
 
 
 
 
 
 
37a6ee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
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
149
150
151
152
153
154
155
156
157
---
title: Querymind Api
emoji: πŸ“Š
colorFrom: blue
colorTo: pink
sdk: docker
pinned: false
---

# Natural Language Data Analyst

## Overview
A powerful full-stack analytical web application that enables users to query structured databases using plain, conversational English. The system automatically converts natural language questions into highly optimized, dialect-specific SQL, executes it against an embedded SQLite database, renders beautiful responsive charts (pure SVG without third-party chart libraries), and synthesizes qualitative business insights from the results using generative AI.

## Features
- πŸ—£οΈ **Natural language to SQL conversion**: Translates conversational questions into accurate SQLite SELECT queries.
- πŸ“Š **Auto-generated charts**: Renders pure-SVG Bar, Line, and Pie charts dynamically based on query results column metadata (completely zero-dependency).
- πŸ’‘ **AI-generated insights**: Summarizes query execution results into concise business insights in real time.
- πŸ“ **Upload your own CSV datasets**: Seamlessly upload custom CSV files which are automatically formatted, sanitized, and loaded into individual SQLite database files.
- πŸ—ƒοΈ **Built-in sample datasets**: Pre-loaded with Sales, Employees, and E-commerce sample data to start querying immediately.
- πŸ”„ **Auto-retry on SQL errors**: Automatically catches execution syntax/type failures and prompts the LLM to fix the query (up to 3 retries).
- πŸ“₯ **Export results as CSV**: Downloads query data instantly as CSV files named based on the source question.
- πŸ’‘ **Query Suggestions**: Generates and caches 6 interesting question suggestions using AI when a dataset is opened.
- πŸ•’ **Recent Queries Log**: Retains the last 20 queries run during a session for rapid re-execution.
- ⌨️ **Keyboard Shortcuts**: Focuses input with `Ctrl+K`, submits with `Ctrl+Enter`, and pulls the last query using the `Arrow Up` key when empty.

## Tech Stack

| Technology | Purpose |
|---|---|
| **Python 3.10+ / FastAPI** | Backend web server and REST API routing |
| **Groq (Llama 3.1 8B)** | Advanced SQL query generation, self-correction, suggestions, and text insights |
| **SQLite + Pandas** | SQL database storage, schema analysis, and query execution |
| **React + Vite** | High-performance, reactive single-page frontend application |
| **Pure CSS / HTML5** | Modern, premium glassmorphism dark-mode styling and UI aesthetics |
| **Pure SVG** | High-fidelity interactive charts and visual graphs (zero-dependency) |

---

## Project Structure

```text
nl-data-analyst/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ main.py                 # FastAPI routing, CORS middleware, and cache setup
β”‚   β”œβ”€β”€ config.py               # Global server constants, LLM model selection, and API keys
β”‚   β”œβ”€β”€ schemas.py              # Pydantic models validating REST request and response contracts
β”‚   β”œβ”€β”€ requirements.txt        # Python dependency manifest (FastAPI, Groq, Pandas)
β”‚   └── services/               # Core business logic handlers
β”‚       β”œβ”€β”€ csv_service.py      # CSV loading, parsing, and SQLite DB generation
β”‚       β”œβ”€β”€ sql_service.py      # SQLite execution, query sanitization, and safety audits
β”‚       β”œβ”€β”€ llm_service.py      # SQL generation, self-repair pipelines, and suggestions
β”‚       └── insight_service.py  # Text synthesis translating tabular data to business insights
β”œβ”€β”€ databases/                  # Storage directory containing generated SQLite .db files
β”œβ”€β”€ sample_data/                # Built-in sample CSV datasets (Sales, Employees, E-commerce)
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/         # Reusable React UI component layers
β”‚   β”‚   β”‚   β”œβ”€β”€ Sidebar.jsx     # Side menu listing datasets, upload buttons, and recent logs
β”‚   β”‚   β”‚   β”œβ”€β”€ UploadView.jsx  # Drag-and-drop CSV upload landing zone
β”‚   β”‚   β”‚   β”œβ”€β”€ DataPreview.jsx # Overview statistics, column schema, and data grid preview
β”‚   β”‚   β”‚   β”œβ”€β”€ QueryView.jsx   # Context bars, query log panels, and suggestions decks
β”‚   β”‚   β”‚   β”œβ”€β”€ QueryInput.jsx  # Query textarea form with key shortcut binds
β”‚   β”‚   β”‚   β”œβ”€β”€ QueryResult.jsx # Collapsible SQL, data table, and chart selector display
β”‚   β”‚   β”‚   β”œβ”€β”€ ChartView.jsx   # SVG chart routing, scaling, grid plotting, and tooltips
β”‚   β”‚   β”‚   β”œβ”€β”€ DataTable.jsx   # Interactive data matrix grid
β”‚   β”‚   β”‚   └── LoadingResult.jsx # Dynamic shimmers skeleton loading placeholders
β”‚   β”‚   β”œβ”€β”€ api.js              # JavaScript fetch integration layer mapping REST endpoints
β”‚   β”‚   β”œβ”€β”€ App.jsx             # Top-level state coordinator, stats bar, and toast managers
β”‚   β”‚   β”œβ”€β”€ index.css           # Global custom CSS styles, animations, and responsive queries
β”‚   β”‚   └── main.jsx            # React client DOM mounter
β”‚   β”œβ”€β”€ package.json            # Node.js dev server and build tool dependencies
β”‚   β”œβ”€β”€ vite.config.js          # Vite custom proxy and build settings
β”‚   └── index.html              # Main HTML skeleton file
β”œβ”€β”€ .env                        # Environment credentials (API keys, ports)
└── README.md                   # Project documentation manual
```

---

## Getting Started

### Prerequisites
- **Python 3.10+**
- **Node.js 18+**
- **Groq API Key** (obtain free from [console.groq.com](https://console.groq.com))

### Installation & Running

#### 1. Setup the Backend
Navigate to the root directory and create a virtual environment:
```bash
# Create python virtual environment
python -m venv .venv

# Activate the virtual environment
# On Windows (Command Prompt/PowerShell):
.venv\Scripts\activate
# On macOS/Linux:
source .venv/bin/activate

# Install backend dependencies
pip install -r backend/requirements.txt
```

Create a `.env` configuration file in the project root (using `.env.template` as a model) and fill in your Groq API Key:
```env
GROQ_API_KEY=gsk_your_actual_groq_api_key_here
PORT=8000
```

Start the backend FastAPI server:
```bash
# Run the backend using Uvicorn
python -m uvicorn backend.main:app --host 127.0.0.1 --port 8000 --reload
```
The API documentation will be available at `http://127.0.0.1:8000/docs`.

#### 2. Setup the Frontend
Open a new terminal session, navigate to the `frontend/` directory, install packages, and start the development server:
```bash
cd frontend

# Install client packages
npm install

# Start Vite dev environment
npm run dev -- --port 5173 --host 127.0.0.1
```
The web application is now active at `http://127.0.0.1:5173/`.

---

## How It Works

1. **Dataset Selection & Conversion**: The user selects a preloaded dataset or drops in a custom CSV file. The backend parses it using Pandas and maps datatypes to create an optimized SQLite database file inside the `databases/` folder.
2. **Dynamic Question Suggestions**: When a dataset is loaded, its schema is analysed and passed to the Llama model on Groq to compile 6 business-relevant query suggestions. Suggestions are cached in-memory.
3. **Natural Language Translation**: The user submits a conversational question. The LLM translates the query based on the table schema and SQL formatting system prompts.
4. **Execution & Self-Correction**: The SQLite query is verified against destructive SQL keywords (only SELECTs allowed) and executed. If SQLite throws a syntax error, the LLM-service receives the failing SQL and stacktrace to attempt self-correction.
5. **Visualization Layout**: The frontend parses the output matrix. If column headers contain labels + numbers, it charts the data:
   - **Pie Chart**: Used for $\le 6$ distinct labels (great for composition summaries).
   - **Bar Chart**: Generates dynamic scale sizes and plots vertical bars with custom hover tooltips.
   - **Line Chart**: Draws line series, highlights points, and adds linear gradients under the curves.
6. **Insight Synthesis**: Groq translates the final matrix rows and original question to output a concise 2-3 sentence business summary.

---

## Future Improvements
- **PostgreSQL / MySQL Connectors**: Run natural language analytics on enterprise production databases.
- **Multi-Table JOIN Support**: Incorporate relational schema graphs to query complex multi-table relationships.
- **Dashboard View**: Pin multiple query results cards and auto-refresh reports.
- **Interactive Visualizations**: Modify chart styles, axes, and colors using conversational commands.
- **PDF Exporter**: Export the full history log along with SVG charts and text insights into a PDF report document.

## License
MIT