charantejapolavarapu commited on
Commit
a52cd57
·
verified ·
1 Parent(s): 9e6d188

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -106
app.py CHANGED
@@ -1,121 +1,108 @@
1
  import gradio as gr
2
- import requests
3
- import os
4
  import json
5
- from langdetect import detect
6
  import pandas as pd
7
  from datetime import datetime
8
 
9
- HF_TOKEN = os.getenv("HF_TOKEN")
10
- API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
11
- headers = {"Authorization": f"Bearer {HF_TOKEN}"}
12
-
13
- # Load FAQ
14
- with open("faq.json", "r") as f:
15
- faq_data = json.load(f)
16
-
17
- # Load memory
18
- if os.path.exists("memory.json"):
19
- with open("memory.json", "r") as f:
20
- memory = json.load(f)
21
- else:
22
- memory = {}
23
-
24
- business_info = """
25
- Business Name: SevaBot AI Support
26
- Location: Hyderabad
27
- Working Hours: 10 AM - 9 PM
28
- Return Policy: 7 days replacement only
29
- Delivery Time: 2-3 working days
30
- """
31
-
32
- def check_faq(question):
33
- for item in faq_data:
34
- if question.lower() in item["question"].lower():
35
- return item["answer"]
36
- return None
37
-
38
- def save_memory(user, message, response):
39
- if user not in memory:
40
- memory[user] = []
41
- memory[user].append({
42
- "time": str(datetime.now()),
43
- "message": message,
44
- "response": response
45
- })
46
- with open("memory.json", "w") as f:
47
- json.dump(memory, f, indent=4)
48
-
49
- def ai_response(message):
50
- prompt = f"""
51
- You are a helpful customer support assistant.
52
-
53
- Business Info:
54
- {business_info}
55
-
56
- Customer Question:
57
- {message}
58
- """
59
-
60
- payload = {
61
- "inputs": prompt,
62
- "parameters": {"max_new_tokens": 200, "temperature": 0.5}
63
- }
64
-
65
- response = requests.post(API_URL, headers=headers, json=payload)
66
-
67
- if response.status_code != 200:
68
- return "Sorry, AI service unavailable."
69
-
70
- result = response.json()
71
- return result[0]["generated_text"]
72
-
73
- def respond(message, history, user_id):
74
- try:
75
- language = detect(message)
76
- except:
77
- language = "en"
78
-
79
- # Check FAQ first
80
- faq_answer = check_faq(message)
81
- if faq_answer:
82
- response = faq_answer
83
- else:
84
- response = ai_response(message)
85
-
86
- # Telugu auto handling (basic)
87
- if language == "te":
88
- response = "మీ ప్రశ్నకు సమాధానం:\n" + response
89
-
90
- save_memory(user_id, message, response)
91
- return response
92
-
93
- def admin_dashboard():
94
- data = []
95
- for user, chats in memory.items():
96
- for chat in chats:
97
- data.append({
98
- "User": user,
99
- "Time": chat["time"],
100
- "Message": chat["message"]
101
  })
102
- df = pd.DataFrame(data)
103
- return df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  with gr.Blocks() as demo:
106
- gr.Markdown("## 🤖 SevaBot AI - Smart Customer Support")
107
 
108
- user_id = gr.Textbox(label="Enter Customer ID")
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
- chatbot = gr.ChatInterface(
111
- fn=lambda msg, hist: respond(msg, hist, user_id.value),
112
- title="Customer Chat"
 
 
 
113
  )
114
 
115
- gr.Markdown("## 📊 Admin Dashboard")
116
- admin_btn = gr.Button("View Customer Data")
117
- output_table = gr.Dataframe()
 
 
118
 
119
- admin_btn.click(admin_dashboard, outputs=output_table)
 
 
 
 
 
 
 
 
120
 
121
  demo.launch()
 
1
  import gradio as gr
 
 
2
  import json
 
3
  import pandas as pd
4
  from datetime import datetime
5
 
6
+ # Load products
7
+ with open("products.json", "r") as f:
8
+ products = json.load(f)
9
+
10
+ cart = []
11
+
12
+ def filter_products(category):
13
+ return [
14
+ f"{p['id']} - {p['name']} ({p['brand']}) | ₹{p['price']} per {p['unit']} | Stock: {p['stock']}"
15
+ for p in products if p["category"] == category
16
+ ]
17
+
18
+ def add_to_cart(product_id, quantity):
19
+ for p in products:
20
+ if p["id"] == int(product_id):
21
+ if quantity > p["stock"]:
22
+ return "Not enough stock available!"
23
+
24
+ total = quantity * p["price"]
25
+
26
+ cart.append({
27
+ "Product": p["name"],
28
+ "Brand": p["brand"],
29
+ "Quantity": quantity,
30
+ "Unit": p["unit"],
31
+ "Price": p["price"],
32
+ "Total": total
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  })
34
+
35
+ p["stock"] -= quantity
36
+ return f"{p['name']} added to cart!"
37
+
38
+ return "Product not found!"
39
+
40
+ def view_cart():
41
+ if not cart:
42
+ return pd.DataFrame()
43
+
44
+ return pd.DataFrame(cart)
45
+
46
+ def generate_bill():
47
+ if not cart:
48
+ return "Cart is empty!"
49
+
50
+ df = pd.DataFrame(cart)
51
+ grand_total = df["Total"].sum()
52
+
53
+ bill_text = "🧾 Supermarket Bill\n"
54
+ bill_text += "---------------------------------\n"
55
+
56
+ for item in cart:
57
+ bill_text += f"{item['Product']} - {item['Quantity']} {item['Unit']} = ₹{item['Total']}\n"
58
+
59
+ bill_text += "---------------------------------\n"
60
+ bill_text += f"Grand Total: ₹{grand_total}\n"
61
+ bill_text += f"Date: {datetime.now()}\n"
62
+
63
+ return bill_text
64
+
65
 
66
  with gr.Blocks() as demo:
67
+ gr.Markdown("# 🛒 Smart Supermarket System")
68
 
69
+ category = gr.Dropdown(
70
+ choices=["Groceries", "Personal Care", "Cleaning"],
71
+ label="Select Category"
72
+ )
73
+
74
+ product_list = gr.Dropdown(label="Products")
75
+
76
+ quantity = gr.Number(label="Quantity", value=1)
77
+
78
+ add_btn = gr.Button("Add to Cart")
79
+
80
+ cart_table = gr.Dataframe(label="Cart")
81
+
82
+ bill_output = gr.Textbox(label="Generated Bill")
83
 
84
+ bill_btn = gr.Button("Generate Bill")
85
+
86
+ category.change(
87
+ lambda x: filter_products(x),
88
+ inputs=category,
89
+ outputs=product_list
90
  )
91
 
92
+ add_btn.click(
93
+ add_to_cart,
94
+ inputs=[product_list, quantity],
95
+ outputs=bill_output
96
+ )
97
 
98
+ add_btn.click(
99
+ view_cart,
100
+ outputs=cart_table
101
+ )
102
+
103
+ bill_btn.click(
104
+ generate_bill,
105
+ outputs=bill_output
106
+ )
107
 
108
  demo.launch()