Suva commited on
Commit
d74e960
1 Parent(s): 5646bef

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -0
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import required libraries
2
+ import os
3
+ import openai
4
+ import streamlit as st
5
+ import pandas as pd
6
+ from sqlalchemy import create_engine, text
7
+ from PIL import Image
8
+ from dotenv import load_dotenv
9
+ # Load environment variables from .env file
10
+ load_dotenv()
11
+
12
+ temp_db = create_engine('sqlite:///:memory:', echo=True)
13
+
14
+ # Function to create table definition prompt
15
+ def create_table_definition_prompt(col_input):
16
+ prompt = '''### sqlite SQL table, with its properties:
17
+ #
18
+ # Sales({})
19
+ #
20
+ '''.format(",".join(str(x) for x in col_input))
21
+ return prompt
22
+
23
+
24
+ # Function to combine prompts
25
+ def combine_prompts(col_input, query_prompt):
26
+ definition = create_table_definition_prompt(col_input)
27
+ query_init_string = f"### A query to answer: {query_prompt}\nSELECT"
28
+ return definition + query_init_string
29
+
30
+
31
+ # Function to execute SQL query
32
+ def get_sql(nlp_text, field_input):
33
+ print(nlp_text)
34
+ print(field_input)
35
+ response = openai.Completion.create(
36
+ model="text-davinci-003",
37
+ prompt=combine_prompts(field_input, nlp_text),
38
+ temperature=0,
39
+ max_tokens=150,
40
+ top_p=1.0,
41
+ frequency_penalty=0.0,
42
+ presence_penalty=0.0,
43
+ stop=["#", ";"]
44
+ )
45
+ query = response["choices"][0]["text"]
46
+ if query.startswith(" "):
47
+ query = "SELECT" + query
48
+ with temp_db.connect() as conn:
49
+ result = conn.execute(text(query))
50
+ return result.all()
51
+
52
+
53
+ # Read CSV file into DataFrame
54
+ def read_csv_file(uploaded_file):
55
+ try:
56
+ df = pd.read_csv(uploaded_file, encoding="latin1")
57
+ with temp_db.connect() as conn:
58
+ df.to_sql(name='Sales', con=conn, if_exists='replace', index=False)
59
+ return df
60
+ except Exception as e:
61
+ st.error(f"Error occurred while reading the CSV file: {str(e)}")
62
+ return None
63
+
64
+
65
+ # Configure Streamlit page layout and title
66
+ st.set_page_config(
67
+ page_title="Query Builder",
68
+ layout="wide",
69
+ page_icon=":bar_chart:"
70
+ )
71
+
72
+ # Set OpenAI API key
73
+ api_key = os.getenv('OPENAI_API_KEY')
74
+ #api_key = os.environ.get('OPENAI_API_KEY')
75
+ openai.api_key = api_key
76
+
77
+ # Add CSS styles
78
+ st.markdown(
79
+ """
80
+ <style>
81
+ .front-page {
82
+ background-color: #f5f5f5;
83
+ padding: 20px;
84
+ border-radius: 10px;
85
+ }
86
+ </style>
87
+ """,
88
+ unsafe_allow_html=True
89
+ )
90
+
91
+ hide_streamlit_style = """
92
+ <style>
93
+ #MainMenu {visibility: hidden;}
94
+ footer {visibility: hidden;}
95
+ </style>
96
+ """
97
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)
98
+
99
+ col1, col2 = st.columns([1, 2])
100
+ with col1:
101
+ pass
102
+ with col2:
103
+ image = Image.open('D:/vscode/qb/data/comsense-Logo2.png')
104
+ resized_image = image.resize((1200, 400)) # Adjust the size as per your requirement
105
+ st.image(resized_image, width=180)
106
+
107
+ # Front page content
108
+ st.title(":bar_chart: Query Builder")
109
+ #st.markdown('<div class="front-page">', unsafe_allow_html=True)
110
+ st.title("Please write your *Query* Here :arrow_down_small:")
111
+ input_value = st.text_input("", " ")
112
+ st.markdown('</div>', unsafe_allow_html=True)
113
+
114
+ # Sidebar - CSV file upload
115
+ uploaded_file = st.sidebar.file_uploader("Upload CSV File")
116
+
117
+ # Process uploaded CSV file
118
+ if uploaded_file is not None:
119
+ df = read_csv_file(uploaded_file)
120
+ if df is not None:
121
+ st.sidebar.dataframe(df)
122
+
123
+ # Execute SQL query and display result
124
+ if st.button("Run Query"):
125
+ if uploaded_file is not None and df is not None:
126
+ try:
127
+ field_input =df.columns
128
+ final_result = get_sql(input_value, field_input)
129
+ output_column, _ = st.columns(2)
130
+ with output_column:
131
+ st.title("Output")
132
+ if isinstance(final_result, list):
133
+ final_result = pd.DataFrame(final_result)
134
+ show_data = st.dataframe(final_result.style.set_properties(**{'font-size': '12px', 'text-align': 'center'}))
135
+ except Exception as e:
136
+ st.error("Please try again with simple sentence.")
137
+ else:
138
+ st.warning("Please upload a valid CSV file first.")