MHD011 commited on
Commit
665b459
·
verified ·
1 Parent(s): a8212fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -14
app.py CHANGED
@@ -132,7 +132,7 @@ def validate_cam_mac(cam_mac):
132
 
133
  # --- توليد SQL باستخدام Gemini مع تخصيص حسب cam_mac ---
134
  def generate_sql_gemini(natural_language_query, cam_mac):
135
- prompt = f"""YYou are a PostgreSQL expert.
136
  Your job is to convert a natural language query into a SQL SELECT statement, based on the following database schema.
137
 
138
  The query **must always be filtered by the camera MAC address: '{cam_mac}'**, using the appropriate field.
@@ -246,23 +246,35 @@ def handle_query():
246
  cursor.execute(sql_query)
247
  columns = [desc[0] for desc in cursor.description]
248
  rows = cursor.fetchall()
249
- data = [dict(zip(columns, row)) for row in rows]
250
-
251
- response_data = {
252
- "data": data,
253
- }
254
 
255
- response_json = json.dumps(response_data, ensure_ascii=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
 
257
- return Response(
258
- response_json,
259
- status=200,
260
- mimetype='application/json; charset=utf-8'
261
- )
262
 
263
  except Exception as e:
264
  print(f"SQL execution error: {e}")
265
- return jsonify({"error": str(e), "generated_sql": sql_query}), 500
 
 
 
 
266
  finally:
267
  if cursor:
268
  cursor.close()
@@ -277,4 +289,4 @@ def home():
277
  """
278
 
279
  if __name__ == '__main__':
280
- app.run(host='0.0.0.0', port=7860)
 
132
 
133
  # --- توليد SQL باستخدام Gemini مع تخصيص حسب cam_mac ---
134
  def generate_sql_gemini(natural_language_query, cam_mac):
135
+ prompt = f"""You are a PostgreSQL expert.
136
  Your job is to convert a natural language query into a SQL SELECT statement, based on the following database schema.
137
 
138
  The query **must always be filtered by the camera MAC address: '{cam_mac}'**, using the appropriate field.
 
246
  cursor.execute(sql_query)
247
  columns = [desc[0] for desc in cursor.description]
248
  rows = cursor.fetchall()
 
 
 
 
 
249
 
250
+ # تحويل النتائج إلى قائمة من القواميس
251
+ result_data = []
252
+ for row in rows:
253
+ row_dict = {}
254
+ for i, col in enumerate(columns):
255
+ # تحويل أنواع البيانات غير القابلة للتسلسل JSON
256
+ if isinstance(row[i], (datetime.date, datetime.time, datetime.datetime)):
257
+ row_dict[col] = str(row[i])
258
+ else:
259
+ row_dict[col] = row[i]
260
+ result_data.append(row_dict)
261
+
262
+ response = {
263
+ "status": "success",
264
+ "data": result_data,
265
+ "query": natural_query,
266
+ "sql_query": sql_query
267
+ }
268
 
269
+ return jsonify(response)
 
 
 
 
270
 
271
  except Exception as e:
272
  print(f"SQL execution error: {e}")
273
+ return jsonify({
274
+ "status": "error",
275
+ "message": str(e),
276
+ "generated_sql": sql_query
277
+ }), 500
278
  finally:
279
  if cursor:
280
  cursor.close()
 
289
  """
290
 
291
  if __name__ == '__main__':
292
+ app.run(host='0.0.0.0', port=7860)