Parishri07 commited on
Commit
943ca21
Β·
verified Β·
1 Parent(s): 42fe318

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -81
app.py CHANGED
@@ -1,95 +1,66 @@
1
- import gradio as gr
2
  import pandas as pd
3
- import re
4
- from huggingface_hub import InferenceClient
5
 
6
- # Load inventory dataset
7
  df = pd.read_csv("inventory.csv")
8
 
9
- # Hugging Face LLM client
10
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
11
 
12
- # 🧞 RetailGenie logic
13
- def retailgenie_query(user_input: str) -> str:
14
- user_input = user_input.lower()
15
-
16
- if "where can i find" in user_input:
17
- product = user_input.split("find")[-1].strip()
18
- match = df[df['Product Name'].str.lower().str.contains(product)]
19
- if not match.empty:
20
- return f"{product.title()} is in {match.iloc[0]['Aisle']}."
21
- else:
22
- return "Sorry, I couldn't find that product."
23
 
24
- elif "in stock" in user_input:
25
- product = re.sub(r"(is|in stock|\?)", "", user_input).strip()
26
- match = df[df['Product Name'].str.lower().str.contains(product)]
27
- if not match.empty:
28
- return f"{product.title()} is {'available' if match.iloc[0]['In Stock'].lower() == 'yes' else 'out of stock'}."
29
- else:
30
- return "Product not found."
31
-
32
- elif "suggest" in user_input and "under" in user_input:
33
- category = user_input.split("suggest a")[-1].split("under")[0].strip()
34
- try:
35
- price = int(re.findall(r"\d+", user_input)[-1])
36
- except:
37
- return "Please enter a valid price."
38
- matches = df[(df['Category'].str.lower().str.contains(category)) & (df['Price (rupees)'] <= price)]
39
- if not matches.empty:
40
- return "Here are some options: " + ", ".join(matches['Product Name'].values[:3])
41
- else:
42
- return "No items found in that range."
43
 
44
- elif "deal" in user_input or "deals" in user_input:
45
- electronics = df[df['Category'].str.lower() == "electronics"]
46
- deals = electronics[electronics['Price (rupees)'] < 5000]
47
- if not deals.empty:
48
- return "Deals: " + ", ".join(deals['Product Name'].values[:3])
 
 
 
49
  else:
50
- return "No current deals found in electronics."
 
 
51
 
52
- return None # Not a RetailGenie-style query
 
 
 
53
 
54
- # πŸ” Unified response function
55
- def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p):
56
- # First try product-aware logic
57
- rg_reply = retailgenie_query(message)
58
- if rg_reply:
59
- yield rg_reply
60
- return
 
 
 
 
 
 
61
 
62
- # Else use LLM
63
- messages = [{"role": "system", "content": system_message}]
64
- for user, assistant in history:
65
- if user: messages.append({"role": "user", "content": user})
66
- if assistant: messages.append({"role": "assistant", "content": assistant})
67
- messages.append({"role": "user", "content": message})
68
 
69
- response = ""
70
- for msg in client.chat_completion(
71
- messages,
72
- max_tokens=max_tokens,
73
- stream=True,
74
- temperature=temperature,
75
- top_p=top_p,
76
- ):
77
- token = msg.choices[0].delta.content
78
- response += token
79
- yield response
80
 
81
- # 🧠 Gradio Chat UI
82
- demo = gr.ChatInterface(
83
- respond,
84
- title="🧞 RetailGenie",
85
- description="Ask me where to find products, check availability, get price-based suggestions, or talk to an AI.",
86
- additional_inputs=[
87
- gr.Textbox(value="You are a helpful retail assistant.", label="System message"),
88
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
89
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
90
- gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
91
- ]
92
- )
93
 
94
- if __name__ == "__main__":
95
- demo.launch()
 
 
1
  import pandas as pd
2
+ import gradio as gr
 
3
 
4
+ # Load inventory
5
  df = pd.read_csv("inventory.csv")
6
 
7
+ # Extract category list
8
+ categories = sorted(df['Category'].dropna().unique())
9
 
10
+ # Step 1: Ask for category
11
+ def ask_category():
12
+ return "Please select a product category:", gr.Dropdown(choices=categories, label="Product Category"), None
 
 
 
 
 
 
 
 
13
 
14
+ # Step 2: Based on category, ask for product
15
+ def ask_product(category):
16
+ products = df[df['Category'] == category]['Product Name'].unique().tolist()
17
+ return (
18
+ f"Now select a product from {category}:",
19
+ gr.Dropdown(choices=products, label="Product Name"),
20
+ category
21
+ )
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Step 3: Show product info
24
+ def show_result(product, category):
25
+ match = df[(df['Category'] == category) & (df['Product Name'] == product)]
26
+
27
+ if not match.empty:
28
+ row = match.iloc[0]
29
+ if row["In Stock"].strip().lower() == "yes":
30
+ return f"βœ… Your **{product}** is in **{row['Aisle']}**. Quantity available: **{row['Quantity']}**, Price: β‚Ή{row['Price (rupees)']}."
31
  else:
32
+ return f"❌ Sorry, **{product}** is currently **not available** in stock."
33
+ else:
34
+ return "Product not found."
35
 
36
+ # Gradio interface with state
37
+ with gr.Blocks(title="🧞 RetailGenie Guided Assistant") as demo:
38
+ gr.Markdown("## πŸ›οΈ RetailGenie – Smart In-Store Assistant")
39
+ gr.Markdown("Start by selecting a product category:")
40
 
41
+ state_category = gr.State()
42
+
43
+ # Step 1
44
+ cat_btn = gr.Button("Select Category")
45
+ cat_out = gr.Textbox(label="Message")
46
+ cat_dropdown = gr.Dropdown(choices=categories, visible=False)
47
+
48
+ # Step 2
49
+ prod_out = gr.Textbox(label="Message")
50
+ prod_dropdown = gr.Dropdown(visible=False)
51
+
52
+ # Step 3
53
+ final_out = gr.Textbox(label="Result")
54
 
55
+ # Step 1 callback
56
+ def show_cat_options():
57
+ return "Please choose a product category:", gr.update(visible=True), None
58
+ cat_btn.click(show_cat_options, outputs=[cat_out, cat_dropdown, state_category])
 
 
59
 
60
+ # Step 2 callback
61
+ cat_dropdown.change(ask_product, inputs=cat_dropdown, outputs=[prod_out, prod_dropdown, state_category])
 
 
 
 
 
 
 
 
 
62
 
63
+ # Step 3 callback
64
+ prod_dropdown.change(show_result, inputs=[prod_dropdown, state_category], outputs=final_out)
 
 
 
 
 
 
 
 
 
 
65
 
66
+ demo.launch()