arjunanand13 commited on
Commit
2fb8b13
·
verified ·
1 Parent(s): 77a4e9c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -9
app.py CHANGED
@@ -12,31 +12,39 @@ genai_model = genai.GenerativeModel('gemini-pro')
12
 
13
  class SQLPromptModel:
14
  def __init__(self, database):
 
15
  self.database = database
16
  self.conn = sqlite3.connect(self.database)
17
 
18
  def fetch_table_schema(self, table_name):
 
19
  cursor = self.conn.cursor()
 
 
20
  cursor.execute(f"PRAGMA table_info({table_name})")
21
  schema = cursor.fetchall()
22
  return schema if schema else None
23
 
24
  def text2sql_gemini(self, schema, user_prompt, inp_prompt=None):
 
25
  table_columns = ', '.join([f"{col[1]} {col[2]}" for col in schema])
26
 
 
27
  prompt = f"""Below are SQL table schemas paired with instructions that describe a task.
28
  Using valid SQLite, write a response that appropriately completes the request for the provided tables.
29
  ### Instruction: {user_prompt} ###
30
  Input: CREATE TABLE sql_pdf({table_columns});
31
  ### Response: (Return only generated query based on user_prompt , nothing extra)"""
32
 
 
33
  if inp_prompt is not None:
34
  prompt = prompt.replace(user_prompt, inp_prompt + " ")
35
 
 
36
  completion = genai_model.generate_content(prompt)
37
  generated_query = completion.text
38
 
39
- # Extract SQL query
40
  start_index = generated_query.find("SELECT")
41
  end_index = generated_query.find(";", start_index) + 1
42
 
@@ -45,74 +53,87 @@ class SQLPromptModel:
45
  return generated_query
46
 
47
  def execute_query(self, query):
 
48
  cur = self.conn.cursor()
49
  cur.execute(query)
 
50
  columns = [header[0] for header in cur.description]
 
51
  rows = [row for row in cur.fetchall()]
52
  cur.close()
53
  self.conn.commit()
54
  return rows, columns
55
 
56
  def execute_sql_query(input_prompt):
 
57
  database = r"sql_pdf.db"
58
  sql_model = SQLPromptModel(database)
59
 
 
60
  user_prompt = "Give complete details of properties in India"
61
 
62
- for _ in range(3): # Retry logic
 
63
  try:
 
64
  table_schema = sql_model.fetch_table_schema("sql_pdf")
65
  if table_schema:
 
66
  if input_prompt.strip():
67
  query = sql_model.text2sql_gemini(table_schema, user_prompt, input_prompt)
68
  else:
69
  query = sql_model.text2sql_gemini(table_schema, user_prompt, user_prompt)
70
 
71
  rows, columns = sql_model.execute_query(query)
 
72
  return {"Query": query, "Results": rows, "Columns": columns}
73
  else:
74
  return {"error": "Table schema not found."}
75
  except Exception as e:
76
  print(f"An error occurred: {e}")
77
- time.sleep(1)
78
  return {"error": "Failed to execute query after 3 retries."}
79
 
80
  # Load the image
 
81
  image = Image.open(os.path.join(os.path.abspath(''), "house_excel_sheet.png"))
82
 
83
- # Create Gradio interface
84
  with gr.Blocks(title="House Database Query") as demo:
 
85
  gr.Markdown("# House Database Query System")
86
 
87
- # Display the image
88
  gr.Image(image)
89
 
 
90
  gr.Markdown("""### The database contains information about different properties including their fundamental details.
91
  You can query this database using natural language.""")
92
 
 
93
  with gr.Row():
94
- # Query input and output
95
  query_input = gr.Textbox(
96
  lines=2,
97
  label="Database Query",
98
  placeholder="Enter your query or choose from examples below. Default: 'Properties in India'"
99
  )
100
 
 
101
  with gr.Row():
102
- # Add submit button
103
  submit_btn = gr.Button("Submit Query", variant="primary")
104
 
 
105
  with gr.Row():
106
  query_output = gr.JSON(label="Query Results")
107
 
108
- # Connect submit button to the query function
109
  submit_btn.click(
110
  fn=execute_sql_query,
111
  inputs=query_input,
112
  outputs=query_output
113
  )
114
 
115
- # Example queries
116
  gr.Examples(
117
  examples=[
118
  "Properties in France",
 
12
 
13
  class SQLPromptModel:
14
  def __init__(self, database):
15
+ # Initialize with database file path and create connection
16
  self.database = database
17
  self.conn = sqlite3.connect(self.database)
18
 
19
  def fetch_table_schema(self, table_name):
20
+ # Get database table structure
21
  cursor = self.conn.cursor()
22
+ # PRAGMA table_info returns:
23
+ # (id, name, type, notnull, default_value, primary_key)
24
  cursor.execute(f"PRAGMA table_info({table_name})")
25
  schema = cursor.fetchall()
26
  return schema if schema else None
27
 
28
  def text2sql_gemini(self, schema, user_prompt, inp_prompt=None):
29
+ # Convert table columns to string format
30
  table_columns = ', '.join([f"{col[1]} {col[2]}" for col in schema])
31
 
32
+ # Create prompt for Gemini AI
33
  prompt = f"""Below are SQL table schemas paired with instructions that describe a task.
34
  Using valid SQLite, write a response that appropriately completes the request for the provided tables.
35
  ### Instruction: {user_prompt} ###
36
  Input: CREATE TABLE sql_pdf({table_columns});
37
  ### Response: (Return only generated query based on user_prompt , nothing extra)"""
38
 
39
+ # Replace default prompt with user input if provided
40
  if inp_prompt is not None:
41
  prompt = prompt.replace(user_prompt, inp_prompt + " ")
42
 
43
+ # Get SQL query from Gemini
44
  completion = genai_model.generate_content(prompt)
45
  generated_query = completion.text
46
 
47
+ # Extract just the SQL query
48
  start_index = generated_query.find("SELECT")
49
  end_index = generated_query.find(";", start_index) + 1
50
 
 
53
  return generated_query
54
 
55
  def execute_query(self, query):
56
+ # Execute SQL query and get results
57
  cur = self.conn.cursor()
58
  cur.execute(query)
59
+ # Get column names
60
  columns = [header[0] for header in cur.description]
61
+ # Get all rows
62
  rows = [row for row in cur.fetchall()]
63
  cur.close()
64
  self.conn.commit()
65
  return rows, columns
66
 
67
  def execute_sql_query(input_prompt):
68
+ # Database file path
69
  database = r"sql_pdf.db"
70
  sql_model = SQLPromptModel(database)
71
 
72
+ # Default prompt if none provided
73
  user_prompt = "Give complete details of properties in India"
74
 
75
+ # Try operation up to 3 times
76
+ for _ in range(3):
77
  try:
78
+ # Get database structure
79
  table_schema = sql_model.fetch_table_schema("sql_pdf")
80
  if table_schema:
81
+ # Generate and execute query
82
  if input_prompt.strip():
83
  query = sql_model.text2sql_gemini(table_schema, user_prompt, input_prompt)
84
  else:
85
  query = sql_model.text2sql_gemini(table_schema, user_prompt, user_prompt)
86
 
87
  rows, columns = sql_model.execute_query(query)
88
+ # Return formatted results
89
  return {"Query": query, "Results": rows, "Columns": columns}
90
  else:
91
  return {"error": "Table schema not found."}
92
  except Exception as e:
93
  print(f"An error occurred: {e}")
94
+ time.sleep(1) # Wait 1 second before retry
95
  return {"error": "Failed to execute query after 3 retries."}
96
 
97
  # Load the image
98
+ # Load database schema image
99
  image = Image.open(os.path.join(os.path.abspath(''), "house_excel_sheet.png"))
100
 
101
+ # Create web interface
102
  with gr.Blocks(title="House Database Query") as demo:
103
+ # Header
104
  gr.Markdown("# House Database Query System")
105
 
106
+ # Display database schema image
107
  gr.Image(image)
108
 
109
+ # Description
110
  gr.Markdown("""### The database contains information about different properties including their fundamental details.
111
  You can query this database using natural language.""")
112
 
113
+ # Input section
114
  with gr.Row():
 
115
  query_input = gr.Textbox(
116
  lines=2,
117
  label="Database Query",
118
  placeholder="Enter your query or choose from examples below. Default: 'Properties in India'"
119
  )
120
 
121
+ # Submit button section
122
  with gr.Row():
 
123
  submit_btn = gr.Button("Submit Query", variant="primary")
124
 
125
+ # Results section
126
  with gr.Row():
127
  query_output = gr.JSON(label="Query Results")
128
 
129
+ # Connect button click to query function
130
  submit_btn.click(
131
  fn=execute_sql_query,
132
  inputs=query_input,
133
  outputs=query_output
134
  )
135
 
136
+ # Example queries section
137
  gr.Examples(
138
  examples=[
139
  "Properties in France",