SuhasGholkar commited on
Commit
1f7bc21
·
verified ·
1 Parent(s): 39d7698

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -7
app.py CHANGED
@@ -44,9 +44,33 @@ def ensure_db():
44
  local = hf_hub_download(repo_id=repo_id, filename=filename, token=token)
45
  Path(local).replace(p)
46
 
47
- ensure_db()
48
 
49
- MAX_HISTORY = 10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  LOG_FILE = "./app.log"
51
 
52
  # ================= LOGGING =================
@@ -58,10 +82,9 @@ logging.basicConfig(
58
  logger = logging.getLogger(__name__)
59
 
60
  # ================= OPENAI CLIENT (v1) =================
 
61
  API_KEY = os.getenv("OPENAI_API_KEY")
62
- if not API_KEY:
63
- raise ValueError("OPENAI_API_KEY environment variable not set.")
64
- client = OpenAI(api_key=API_KEY)
65
 
66
  # ================= SQLITE HELPERS =================
67
  def get_connection():
@@ -622,6 +645,10 @@ with tab1:
622
  show_hist = st.checkbox("Show conversation history (current session)")
623
 
624
  # --- Submit handler ---
 
 
 
 
625
  if st.button("Submit"):
626
  if st.session_state.user_input.strip():
627
  start_time = time.time()
@@ -648,7 +675,8 @@ with tab1:
648
  if intent == "UNMAPPED":
649
  # Meta label for better UX
650
  meta = gpt_label_unmapped(user_text)
651
- intent = f"{meta}" # <-- store combined string, no DB migration needed
 
652
  bot_reply = gpt_fallback_response(user_text)
653
  resolution = "Responded"
654
  else:
@@ -694,7 +722,7 @@ with tab1:
694
  # Persist (store params only when intent mapped)
695
  try:
696
  save_chat_to_db(user_text, intent, sentiment, resolution, bot_reply, ftr_ms, sql_query,
697
- params if intent != "UNMAPPED" else {})
698
  except Exception:
699
  logger.exception("Failed to save chat history to DB")
700
 
 
44
  local = hf_hub_download(repo_id=repo_id, filename=filename, token=token)
45
  Path(local).replace(p)
46
 
47
+ ensure_db
48
 
49
+ def ensure_views():
50
+ with get_connection() as conn:
51
+ cur = conn.cursor()
52
+ # Detect if short tables exist; if not, create views that map to *_dataset tables
53
+ cur.execute("SELECT name FROM sqlite_master WHERE type IN ('table','view')")
54
+ names = {r[0] for r in cur.fetchall()}
55
+
56
+ def mk_view(short, full):
57
+ if short not in names and full in names:
58
+ conn.execute(f"CREATE VIEW IF NOT EXISTS {short} AS SELECT * FROM {full}")
59
+
60
+ mk_view("olist_orders", "olist_orders_dataset")
61
+ mk_view("olist_order_items", "olist_order_items_dataset")
62
+ mk_view("olist_products", "olist_products_dataset")
63
+ mk_view("olist_customers", "olist_customers_dataset")
64
+ mk_view("olist_order_payments", "olist_order_payments_dataset")
65
+ mk_view("olist_order_reviews", "olist_order_reviews_dataset")
66
+ # Optional: translated categories view alias
67
+ mk_view("product_category_name_translation", "product_category_name_translation")
68
+ conn.commit()
69
+
70
+ ensure_views()
71
+
72
+
73
+ MAX_HISTORY = int(os.getenv("MAX_HISTORY","10"))
74
  LOG_FILE = "./app.log"
75
 
76
  # ================= LOGGING =================
 
82
  logger = logging.getLogger(__name__)
83
 
84
  # ================= OPENAI CLIENT (v1) =================
85
+
86
  API_KEY = os.getenv("OPENAI_API_KEY")
87
+ client = OpenAI(api_key=API_KEY) if API_KEY else None
 
 
88
 
89
  # ================= SQLITE HELPERS =================
90
  def get_connection():
 
645
  show_hist = st.checkbox("Show conversation history (current session)")
646
 
647
  # --- Submit handler ---
648
+ if client is None:
649
+ st.error("OPENAI_API_KEY is not set (Spaces → Settings → Repository secrets).")
650
+ st.stop()
651
+
652
  if st.button("Submit"):
653
  if st.session_state.user_input.strip():
654
  start_time = time.time()
 
675
  if intent == "UNMAPPED":
676
  # Meta label for better UX
677
  meta = gpt_label_unmapped(user_text)
678
+ intent = f"UNMAPPED ({meta})" # <-- store combined string, no DB migration needed
679
+ params = {}
680
  bot_reply = gpt_fallback_response(user_text)
681
  resolution = "Responded"
682
  else:
 
722
  # Persist (store params only when intent mapped)
723
  try:
724
  save_chat_to_db(user_text, intent, sentiment, resolution, bot_reply, ftr_ms, sql_query,
725
+ params if intent in INTENTS else {})
726
  except Exception:
727
  logger.exception("Failed to save chat history to DB")
728