File size: 11,666 Bytes
6a0ec6a
 
91561ce
6a0ec6a
91561ce
1767e22
91561ce
 
 
 
 
 
 
 
a573881
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f776bb6
08d132d
f776bb6
 
 
08d132d
 
 
 
 
 
 
 
 
f776bb6
08d132d
 
 
f776bb6
 
08d132d
f776bb6
08d132d
f776bb6
 
 
 
 
 
 
 
 
 
 
 
08d132d
f776bb6
 
08d132d
e465450
9002697
e465450
28200f6
5a55ea7
e465450
 
 
91561ce
6d10b4f
 
 
e465450
6d10b4f
e465450
 
 
 
 
 
 
6d10b4f
e465450
 
3df9eeb
e465450
 
 
 
08d132d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3df9eeb
08d132d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f776bb6
 
 
 
08d132d
f776bb6
 
08d132d
f776bb6
 
 
 
 
 
 
 
6c1c88d
08d132d
 
 
8dc7735
08d132d
 
8dc7735
08d132d
8dc7735
08d132d
8dc7735
 
 
 
 
 
 
08d132d
f776bb6
 
 
 
 
 
 
 
 
 
 
08d132d
8dc7735
 
 
 
 
 
 
 
 
 
 
08d132d
d870c12
fed63c4
6d10b4f
811c7ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3df9eeb
811c7ec
6d10b4f
91561ce
3df9eeb
 
 
 
 
 
 
 
 
91561ce
 
 
3df9eeb
 
5a55ea7
3df9eeb
 
a573881
 
 
 
 
 
 
3df9eeb
 
6d10b4f
 
a573881
 
 
 
 
3df9eeb
 
 
a573881
3df9eeb
 
 
 
 
 
 
 
 
 
811c7ec
3df9eeb
6d10b4f
a573881
 
 
 
 
 
d870c12
 
811c7ec
 
3df9eeb
6d10b4f
3df9eeb
6d10b4f
3df9eeb
6d10b4f
3df9eeb
6d10b4f
d870c12
 
 
 
3df9eeb
 
d870c12
 
3df9eeb
 
 
811c7ec
6a0ec6a
 
3df9eeb
 
6ed45c1
3df9eeb
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import os
import gradio as gr
from sqlalchemy import text
from smolagents import tool, CodeAgent, HfApiModel
import spaces
import pandas as pd
from database import (
    engine,
    create_dynamic_table,
    clear_database,
    insert_rows_into_table,
    get_table_schema
)

def get_data_table():
    """
    Fetches all data from the current table and returns it as a Pandas DataFrame.
    """
    try:
        # Get list of tables
        with engine.connect() as con:
            tables = con.execute(text(
                "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
            )).fetchall()
            
        if not tables:
            return pd.DataFrame()
            
        # Use the first table found
        table_name = tables[0][0]
            
        with engine.connect() as con:
            result = con.execute(text(f"SELECT * FROM {table_name}"))
            rows = result.fetchall()
            
            if not rows:
                return pd.DataFrame()
                
            columns = result.keys()
            df = pd.DataFrame(rows, columns=columns)
            return df

    except Exception as e:
        return pd.DataFrame({"Error": [str(e)]})

def get_table_info():
    """
    Gets the current table name and column information.
    Returns:
        tuple: (table_name, list of column names, column info)
    """
    try:
        # Get list of tables
        with engine.connect() as con:
            tables = con.execute(text(
                "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
            )).fetchall()
            
        if not tables:
            return None, [], {}
            
        # Use the first table found
        table_name = tables[0][0]
        
        # Get column information
        with engine.connect() as con:
            columns = con.execute(text(f"PRAGMA table_info({table_name})")).fetchall()
            
        # Extract column names and types
        column_names = [col[1] for col in columns]
        column_info = {
            col[1]: {
                'type': col[2],
                'is_primary': bool(col[5])
            }
            for col in columns
        }
        
        return table_name, column_names, column_info
        
    except Exception as e:
        print(f"Error getting table info: {str(e)}")
        return None, [], {}

def process_sql_file(file_path):
    """
    Process an SQL file and execute its contents.
    """
    try:
        # Read the SQL file
        with open(file_path, 'r') as file:
            sql_content = file.read()
            
        # Replace AUTO_INCREMENT with AUTOINCREMENT for SQLite compatibility
        sql_content = sql_content.replace('AUTO_INCREMENT', 'AUTOINCREMENT')
            
        # Split into individual statements
        statements = [stmt.strip() for stmt in sql_content.split(';') if stmt.strip()]
        
        # Clear existing database
        clear_database()
        
        # Execute each statement
        with engine.begin() as conn:
            for statement in statements:
                if statement.strip():
                    conn.execute(text(statement))
                    
        return True, "SQL file successfully executed!"
        
    except Exception as e:
        return False, f"Error processing SQL file: {str(e)}"

def process_csv_file(file_path):
    """
    Process a CSV file and load it into the database.
    """
    try:
        # Read the CSV file
        df = pd.read_csv(file_path)
        
        if len(df.columns) == 0:
            return False, "Error: File contains no columns"
            
        # Clear existing database and create new table
        clear_database()
        table = create_dynamic_table(df)
        
        # Convert DataFrame to list of dictionaries and insert
        records = df.to_dict('records')
        insert_rows_into_table(records, table)
        
        return True, "CSV file successfully loaded!"
        
    except Exception as e:
        return False, f"Error processing CSV file: {str(e)}"

def process_uploaded_file(file):
    """
    Process the uploaded file (either SQL or CSV).
    """
    try:
        if file is None:
            return False, "Please upload a file."
            
        # Get file extension
        file_ext = os.path.splitext(file)[1].lower()
        
        if file_ext == '.sql':
            return process_sql_file(file)
        elif file_ext == '.csv':
            return process_csv_file(file)
        else:
            return False, "Error: Unsupported file type. Please upload either a .sql or .csv file."
            
    except Exception as e:
        return False, f"Error processing file: {str(e)}"

@tool
def sql_engine(query: str) -> str:
    """
    Executes an SQL query and returns formatted results.

    Args:
        query: The SQL query string to execute on the database. Must be a valid SELECT query.

    Returns:
        str: The formatted query results as a string.
    """
    try:
        with engine.connect() as con:
            rows = con.execute(text(query)).fetchall()

        if not rows:
            return "No results found."

        if len(rows) == 1 and len(rows[0]) == 1:
            return str(rows[0][0])

        return "\n".join([", ".join(map(str, row)) for row in rows])

    except Exception as e:
        return f"Error: {str(e)}"

agent = CodeAgent(
    tools=[sql_engine],
    model=HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct"),
)

def query_sql(user_query: str) -> str:
    """
    Converts natural language input to an SQL query using CodeAgent.
    """
    # Get current table information
    table_name, column_names, column_info = get_table_info()
    
    if not table_name:
        return "Error: No data table exists. Please upload a file first."
    
    # Create schema information with actual column names
    schema_info = (
        f"The database has a table named '{table_name}' with the following columns:\n"
        + "\n".join([
            f"- {col} ({info['type']}){' primary key' if info['is_primary'] else ''}"
            for col, info in column_info.items()
        ])
        + "\n\nGenerate a valid SQL SELECT query using ONLY these column names.\n"
        "The table name is '" + table_name + "'.\n"
        "If column names contain spaces, they must be quoted.\n"
        "You can use aggregate functions like COUNT, AVG, SUM, etc.\n"
        "DO NOT explain your reasoning, and DO NOT return anything other than the SQL query itself."
    )

    # Get the SQL query from the agent
    generated_sql = agent.run(f"{schema_info} Convert this request into SQL: {user_query}")

    # Clean up and validate the SQL
    if not isinstance(generated_sql, str):
        return f"Error: Invalid query generated"

    # Extract just the SQL query if there's additional text
    sql_lines = [line for line in generated_sql.split('\n') if 'select' in line.lower()]
    if sql_lines:
        generated_sql = sql_lines[0]

    # Remove any trailing semicolons
    generated_sql = generated_sql.strip().rstrip(';')

    # Fix table names
    for wrong_name in ['table_name', 'customers', 'main']:
        if wrong_name in generated_sql:
            generated_sql = generated_sql.replace(wrong_name, table_name)
    
    # Add quotes around column names that need them
    for col in column_names:
        if ' ' in col:  # If column name contains spaces
            if col in generated_sql and f'"{col}"' not in generated_sql and f'`{col}`' not in generated_sql:
                generated_sql = generated_sql.replace(col, f'"{col}"')

    try:
        # Execute the query
        result = sql_engine(generated_sql)
        
        # Try to format as number if possible
        try:
            float_result = float(result)
            return f"{float_result:,.0f}"  # Format with commas, no decimals
        except ValueError:
            return result
    except Exception as e:
        return f"Error executing query: {str(e)}"

# Create the Gradio interface
with gr.Blocks() as demo:
    with gr.Group() as upload_group:
        gr.Markdown("""
        # Data Query Interface

        Upload your data file to begin.
        
        ### Supported File Types:
        - SQL (.sql): SQL file containing CREATE TABLE and INSERT statements
        - CSV (.csv): CSV file with headers that will be automatically converted to a table
        
        ### CSV Requirements:
        - Must include headers
        - First column will be used as the primary key
        - Column types will be automatically detected
        
        ### SQL Requirements:
        - Must contain valid SQL statements
        - Statements must be separated by semicolons
        - Should include CREATE TABLE and data insertion statements
        """)
        
        file_input = gr.File(
            label="Upload Data File",
            file_types=[".csv", ".sql"],
            type="filepath"
        )
        status = gr.Textbox(label="Status", interactive=False)

    with gr.Group(visible=False) as query_group:
        with gr.Row():
            with gr.Column(scale=1):
                user_input = gr.Textbox(label="Ask a question about the data")
                query_output = gr.Textbox(label="Result")
            
            with gr.Column(scale=2):
                gr.Markdown("### Current Data")
                data_table = gr.Dataframe(
                    value=None,
                    label="Data Table",
                    interactive=False
                )
        
        schema_display = gr.Markdown(value="Loading schema...")
        refresh_btn = gr.Button("Refresh Data")

    def handle_upload(file_obj):
        if file_obj is None:
            return (
                "Please upload a file.",
                None,
                "No schema available",
                gr.update(visible=True),
                gr.update(visible=False)
            )
        
        success, message = process_uploaded_file(file_obj)
        if success:
            df = get_data_table()
            _, _, column_info = get_table_info()
            schema = "\n".join([
                f"- {col} ({info['type']}){' primary key' if info['is_primary'] else ''}"
                for col, info in column_info.items()
            ])
            return (
                message,
                df,
                f"### Current Schema:\n```\n{schema}\n```",
                gr.update(visible=False),
                gr.update(visible=True)
            )
        return (
            message,
            None,
            "No schema available",
            gr.update(visible=True),
            gr.update(visible=False)
        )

    def refresh_data():
        df = get_data_table()
        _, _, column_info = get_table_info()
        schema = "\n".join([
            f"- {col} ({info['type']}){' primary key' if info['is_primary'] else ''}"
            for col, info in column_info.items()
        ])
        return df, f"### Current Schema:\n```\n{schema}\n```"

    # Event handlers
    file_input.upload(
        fn=handle_upload,
        inputs=file_input,
        outputs=[
            status,
            data_table,
            schema_display,
            upload_group,
            query_group
        ]
    )

    user_input.change(
        fn=query_sql,
        inputs=user_input,
        outputs=query_output
    )
    
    refresh_btn.click(
        fn=refresh_data,
        outputs=[data_table, schema_display]
    )

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860
    )