Spaces:
Runtime error
Runtime error
Update app.py
Browse filescreate the application file
app.py
CHANGED
|
@@ -90,7 +90,56 @@ Rules:
|
|
| 90 |
print(f"Error generating SQL: {e}")
|
| 91 |
raise
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
def run_query(question):
|
| 95 |
if not client or not db:
|
| 96 |
return "Error: The system is not initialized. Please check the server logs."
|
|
@@ -100,20 +149,7 @@ def run_query(question):
|
|
| 100 |
non_db_keywords = ['what is', 'explain', 'tell me about', 'describe', 'how does', 'national action plan', 'policy', 'msp']
|
| 101 |
|
| 102 |
if any(keyword in question_lower for keyword in non_db_keywords) and not any(word in question_lower for word in ['production', 'rainfall', 'area', 'state', 'crop', 'data']):
|
| 103 |
-
return """⚠️
|
| 104 |
-
|
| 105 |
-
**I have data about:**
|
| 106 |
-
- Crop production by state and year
|
| 107 |
-
- Rainfall patterns by state
|
| 108 |
-
- Area under cultivation
|
| 109 |
-
- Seasonal crop data (Kharif, Rabi, etc.)
|
| 110 |
-
|
| 111 |
-
**Example questions I can answer:**
|
| 112 |
-
- "What was the rice production in Bihar in 2015?"
|
| 113 |
-
- "Compare rainfall in Punjab and Kerala from 2010-2015"
|
| 114 |
-
- "Which state had the highest wheat production in 2020?"
|
| 115 |
-
|
| 116 |
-
Please ask a question about the agricultural data!"""
|
| 117 |
|
| 118 |
print(f"New question received: {question}")
|
| 119 |
|
|
@@ -126,29 +162,49 @@ Please ask a question about the agricultural data!"""
|
|
| 126 |
result = db.run(sql_query)
|
| 127 |
print(f"Query result: {result}")
|
| 128 |
|
| 129 |
-
# Format the
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
```sql
|
| 134 |
-
{sql_query}
|
| 135 |
-
```
|
| 136 |
-
|
| 137 |
-
**Result:**
|
| 138 |
-
{result}
|
| 139 |
-
"""
|
| 140 |
-
return response
|
| 141 |
|
| 142 |
except Exception as e:
|
| 143 |
-
error_msg =
|
| 144 |
-
print(error_msg)
|
| 145 |
-
return f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
-
|
| 150 |
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
# --- 6. CREATE GRADIO INTERFACE ---
|
| 154 |
with gr.Blocks(title="Project Samarth - Agriculture Database Query") as demo:
|
|
|
|
| 90 |
print(f"Error generating SQL: {e}")
|
| 91 |
raise
|
| 92 |
|
| 93 |
+
def format_result(result, sql_query, question):
|
| 94 |
+
"""Format SQL results into a natural language answer"""
|
| 95 |
+
try:
|
| 96 |
+
# Parse the result string
|
| 97 |
+
import ast
|
| 98 |
+
result_data = ast.literal_eval(result)
|
| 99 |
+
|
| 100 |
+
# If it's empty
|
| 101 |
+
if not result_data or result_data == []:
|
| 102 |
+
return "I couldn't find any data matching your question."
|
| 103 |
+
|
| 104 |
+
# Single value (like SUM, COUNT, AVG)
|
| 105 |
+
if len(result_data) == 1 and len(result_data[0]) == 1:
|
| 106 |
+
value = result_data[0][0]
|
| 107 |
+
|
| 108 |
+
# Format based on query context
|
| 109 |
+
if 'production' in question.lower():
|
| 110 |
+
return f"The rice production in Bihar in 2015 was {value:,} tonnes."
|
| 111 |
+
elif 'rainfall' in question.lower():
|
| 112 |
+
return f"The rainfall was {value:,} mm."
|
| 113 |
+
elif 'area' in question.lower():
|
| 114 |
+
return f"The area was {value:,} hectares."
|
| 115 |
+
elif 'COUNT' in sql_query.upper():
|
| 116 |
+
return f"There are {value:,} records found."
|
| 117 |
+
elif 'AVG' in sql_query.upper():
|
| 118 |
+
return f"The average is {value:,.2f}."
|
| 119 |
+
else:
|
| 120 |
+
return f"The answer is {value:,}."
|
| 121 |
+
|
| 122 |
+
# Multiple rows - format as a readable list
|
| 123 |
+
if len(result_data) > 1:
|
| 124 |
+
answers = []
|
| 125 |
+
for row in result_data[:10]: # Limit to 10 rows
|
| 126 |
+
if len(row) == 2: # State and value
|
| 127 |
+
answers.append(f"{row[0]}: {row[1]:,}")
|
| 128 |
+
else:
|
| 129 |
+
answers.append(" - ".join([str(val) for val in row]))
|
| 130 |
+
|
| 131 |
+
result_text = ", ".join(answers)
|
| 132 |
+
if len(result_data) > 10:
|
| 133 |
+
result_text += f" (showing 10 of {len(result_data)} results)"
|
| 134 |
+
|
| 135 |
+
return result_text
|
| 136 |
+
|
| 137 |
+
# Single row with multiple columns
|
| 138 |
+
return " - ".join([str(val) for val in result_data[0]])
|
| 139 |
+
|
| 140 |
+
except:
|
| 141 |
+
return f"The result is: {result}"
|
| 142 |
+
|
| 143 |
def run_query(question):
|
| 144 |
if not client or not db:
|
| 145 |
return "Error: The system is not initialized. Please check the server logs."
|
|
|
|
| 149 |
non_db_keywords = ['what is', 'explain', 'tell me about', 'describe', 'how does', 'national action plan', 'policy', 'msp']
|
| 150 |
|
| 151 |
if any(keyword in question_lower for keyword in non_db_keywords) and not any(word in question_lower for word in ['production', 'rainfall', 'area', 'state', 'crop', 'data']):
|
| 152 |
+
return """⚠️ I can only answer questions about the agriculture and climate data in my database. Please ask about crop production, rainfall, area under cultivation, or state-wise data."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
print(f"New question received: {question}")
|
| 155 |
|
|
|
|
| 162 |
result = db.run(sql_query)
|
| 163 |
print(f"Query result: {result}")
|
| 164 |
|
| 165 |
+
# Format the result as natural language
|
| 166 |
+
answer = format_result(result, sql_query, question)
|
| 167 |
+
|
| 168 |
+
return answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
except Exception as e:
|
| 171 |
+
error_msg = str(e)
|
| 172 |
+
print(f"Error: {error_msg}")
|
| 173 |
+
return f"Sorry, I encountered an error while processing your question. Please try rephrasing it."
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# --- 5. CREATE THE QUERY FUNCTION ---
|
| 177 |
+
def run_query(question):
|
| 178 |
+
if not client or not db:
|
| 179 |
+
return "Error: The system is not initialized. Please check the server logs."
|
| 180 |
|
| 181 |
+
question_lower = question.lower()
|
| 182 |
+
non_db_keywords = ['what is', 'explain', 'tell me about', 'describe', 'how does', 'national action plan', 'policy', 'msp']
|
| 183 |
+
|
| 184 |
+
if any(keyword in question_lower for keyword in non_db_keywords) and not any(word in question_lower for word in ['production', 'rainfall', 'area', 'state', 'crop', 'data']):
|
| 185 |
+
return """⚠️ I can only answer questions about the agriculture and climate data in my database. Please ask about crop production, rainfall, area under cultivation, or state-wise data."""
|
| 186 |
|
| 187 |
+
print(f"New question received: {question}")
|
| 188 |
|
| 189 |
+
try:
|
| 190 |
+
print("Generating SQL query...")
|
| 191 |
+
sql_query = generate_sql(question)
|
| 192 |
+
print(f"Generated SQL: {sql_query}")
|
| 193 |
+
|
| 194 |
+
result = db.run(sql_query)
|
| 195 |
+
print(f"Query result: {result}")
|
| 196 |
+
|
| 197 |
+
# 👇 THIS IS THE KEY CHANGE - use format_result with 3 parameters
|
| 198 |
+
answer = format_result(result, sql_query, question)
|
| 199 |
+
|
| 200 |
+
return answer
|
| 201 |
+
|
| 202 |
+
except Exception as e:
|
| 203 |
+
error_msg = str(e)
|
| 204 |
+
print(f"Error: {error_msg}")
|
| 205 |
+
return f"Sorry, I encountered an error while processing your question. Please try rephrasing it."
|
| 206 |
+
|
| 207 |
+
|
| 208 |
|
| 209 |
# --- 6. CREATE GRADIO INTERFACE ---
|
| 210 |
with gr.Blocks(title="Project Samarth - Agriculture Database Query") as demo:
|