indhupamula commited on
Commit
3ed4fdc
·
verified ·
1 Parent(s): eeadef0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -0
app.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import sqlite3
4
+ import plotly.express as px
5
+ import tempfile
6
+
7
+ # Optional: OpenAI + LangChain imports if using NL -> SQL
8
+ try:
9
+ from langchain_openai import OpenAI
10
+ from langchain_experimental.sql import SQLDatabaseChain
11
+ from langchain.sql_database import SQLDatabase
12
+ OPENAI_AVAILABLE = True
13
+ except:
14
+ OPENAI_AVAILABLE = False
15
+
16
+ def process_file(file, question):
17
+ if file is None or question.strip() == "":
18
+ return "Upload a file and ask a question.", None, None
19
+
20
+ # Read uploaded file
21
+ try:
22
+ fname = file.name.lower()
23
+ if fname.endswith(".csv"):
24
+ df = pd.read_csv(file.name)
25
+ else:
26
+ df = pd.read_excel(file.name)
27
+ except Exception as e:
28
+ return f"Error reading file: {e}", None, None
29
+
30
+ # Save to temporary SQLite file
31
+ try:
32
+ temp_db_file = tempfile.NamedTemporaryFile(suffix=".db").name
33
+ conn = sqlite3.connect(temp_db_file)
34
+ df.to_sql("data", conn, if_exists="replace", index=False)
35
+ conn.close()
36
+ except Exception as e:
37
+ return f"Error creating database: {e}", None, None
38
+
39
+ # Run natural language -> SQL if OpenAI available
40
+ result_text = "Rule-based: Showing first 5 rows"
41
+ result_df = df.head(5) # Default fallback
42
+
43
+ if OPENAI_AVAILABLE:
44
+ try:
45
+ db = SQLDatabase.from_uri(f"sqlite:///{temp_db_file}")
46
+ llm = OpenAI(temperature=0)
47
+ db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=False)
48
+ result_text = db_chain.run(question)
49
+ # Execute the SQL safely to show result table
50
+ conn = sqlite3.connect(temp_db_file)
51
+ result_df = pd.read_sql_query("SELECT * FROM data LIMIT 100", conn)
52
+ conn.close()
53
+ except Exception as e:
54
+ result_text = f"OpenAI NL->SQL failed, showing fallback: {e}"
55
+ result_df = df.head(5)
56
+
57
+ # Visualization
58
+ fig = None
59
+ try:
60
+ numeric_cols = result_df.select_dtypes(include=['number']).columns.tolist()
61
+ categorical_cols = result_df.select_dtypes(include=['object']).columns.tolist()
62
+
63
+ if numeric_cols and categorical_cols:
64
+ x_col = categorical_cols[0]
65
+ y_col = numeric_cols[0]
66
+ fig = px.bar(result_df, x=x_col, y=y_col, title=f"{y_col} vs {x_col}")
67
+ elif numeric_cols:
68
+ fig = px.line(result_df[numeric_cols])
69
+ elif categorical_cols:
70
+ fig = px.histogram(result_df, x=categorical_cols[0])
71
+ except Exception as e:
72
+ fig = None # fail silently for visualization
73
+
74
+ return result_text, result_df, fig
75
+
76
+ # Gradio Interface
77
+ file_input = gr.File(label="Upload CSV or Excel")
78
+ question_input = gr.Textbox(label="Ask a question in natural language")
79
+ output_text = gr.Textbox(label="Generated Result")
80
+ output_table = gr.Dataframe(label="Query Result")
81
+ output_plot = gr.Plot(label="Visualization")
82
+
83
+ gr.Interface(
84
+ fn=process_file,
85
+ inputs=[file_input, question_input],
86
+ outputs=[output_text, output_table, output_plot],
87
+ live=False,
88
+ title="NL → SQL Query Generator + Visualization",
89
+ description="Upload CSV/Excel, ask natural language questions, and get SQL results with automatic visualizations."
90
+ ).launch()