Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,169 +1,59 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
|
4 |
-
import json
|
5 |
-
import time
|
6 |
-
from typing import Dict, List
|
7 |
-
import concurrent.futures
|
8 |
-
import re
|
9 |
-
from datetime import datetime
|
10 |
|
11 |
-
|
12 |
-
"""
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
"name": "Rubik's Speed Cube Pro Set",
|
39 |
-
"base_price": 1499,
|
40 |
-
"category": ["puzzles", "brain teasers"],
|
41 |
-
"keywords": ["puzzle", "cube", "brain teaser"],
|
42 |
-
"urls": {
|
43 |
-
"amazon": "B07X1Z3YPV",
|
44 |
-
"flipkart": "PUZRUBSPEED123"
|
45 |
-
}
|
46 |
-
},
|
47 |
-
# Add more puzzle products...
|
48 |
-
]
|
49 |
-
}
|
50 |
-
|
51 |
-
class PriceFetcher:
|
52 |
-
"""Handles real-time price fetching from e-commerce sites"""
|
53 |
-
def __init__(self):
|
54 |
-
self.headers = {
|
55 |
-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
56 |
-
}
|
57 |
-
|
58 |
-
async def fetch_amazon_price(self, product_id: str) -> float:
|
59 |
-
"""Fetch price from Amazon (simplified example)"""
|
60 |
-
try:
|
61 |
-
url = f"https://www.amazon.in/dp/{product_id}"
|
62 |
-
response = requests.get(url, headers=self.headers)
|
63 |
-
if response.status_code == 200:
|
64 |
-
soup = BeautifulSoup(response.text, 'html.parser')
|
65 |
-
price_elem = soup.find('span', class_='a-price-whole')
|
66 |
-
if price_elem:
|
67 |
-
return float(re.sub(r'[^\d.]', '', price_elem.text))
|
68 |
-
return None
|
69 |
-
except Exception as e:
|
70 |
-
print(f"Error fetching Amazon price: {str(e)}")
|
71 |
-
return None
|
72 |
-
|
73 |
-
async def fetch_flipkart_price(self, product_id: str) -> float:
|
74 |
-
"""Fetch price from Flipkart (simplified example)"""
|
75 |
-
try:
|
76 |
-
url = f"https://www.flipkart.com/product/{product_id}"
|
77 |
-
response = requests.get(url, headers=self.headers)
|
78 |
-
if response.status_code == 200:
|
79 |
-
soup = BeautifulSoup(response.text, 'html.parser')
|
80 |
-
price_elem = soup.find('div', class_='_30jeq3')
|
81 |
-
if price_elem:
|
82 |
-
return float(re.sub(r'[^\d.]', '', price_elem.text))
|
83 |
-
return None
|
84 |
-
except Exception as e:
|
85 |
-
print(f"Error fetching Flipkart price: {str(e)}")
|
86 |
-
return None
|
87 |
-
|
88 |
-
class RecommendationEngine:
|
89 |
-
"""Handles product recommendations based on user input"""
|
90 |
-
def __init__(self, product_db: ProductDatabase, price_fetcher: PriceFetcher):
|
91 |
-
self.product_db = product_db
|
92 |
-
self.price_fetcher = price_fetcher
|
93 |
-
|
94 |
-
def extract_keywords(self, text: str) -> List[str]:
|
95 |
-
"""Extract relevant keywords from user input"""
|
96 |
-
# Convert to lowercase and split into words
|
97 |
-
words = text.lower().split()
|
98 |
-
|
99 |
-
# Define common categories and their related terms
|
100 |
-
categories = {
|
101 |
-
"gaming": ["game", "gaming", "fps", "shooter", "console"],
|
102 |
-
"puzzles": ["puzzle", "brain teaser", "rubik", "cube"],
|
103 |
-
# Add more categories...
|
104 |
-
}
|
105 |
-
|
106 |
-
# Extract matching keywords
|
107 |
-
keywords = []
|
108 |
-
for word in words:
|
109 |
-
for category, terms in categories.items():
|
110 |
-
if word in terms:
|
111 |
-
keywords.append(category)
|
112 |
-
|
113 |
-
return list(set(keywords))
|
114 |
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
-
#
|
121 |
-
|
122 |
-
if keyword in self.product_db.products:
|
123 |
-
products = self.product_db.products[keyword][:2] # Get top 2 products per category
|
124 |
-
recommendations.extend(products)
|
125 |
|
126 |
-
#
|
127 |
-
|
128 |
-
for product in recommendations:
|
129 |
-
# Fetch prices concurrently
|
130 |
-
amazon_price = await self.price_fetcher.fetch_amazon_price(product['urls'].get('amazon'))
|
131 |
-
flipkart_price = await self.price_fetcher.fetch_flipkart_price(product['urls'].get('flipkart'))
|
132 |
-
|
133 |
-
# Use the lowest available price or fall back to base price
|
134 |
-
current_price = min(
|
135 |
-
filter(None, [amazon_price, flipkart_price, product['base_price']])
|
136 |
-
)
|
137 |
-
|
138 |
-
formatted_recommendations.append({
|
139 |
-
"name": product['name'],
|
140 |
-
"price": f"βΉ{current_price:,.2f}",
|
141 |
-
"links": {
|
142 |
-
"Amazon": f"https://www.amazon.in/dp/{product['urls'].get('amazon')}",
|
143 |
-
"Flipkart": f"https://www.flipkart.com/product/{product['urls'].get('flipkart')}"
|
144 |
-
}
|
145 |
-
})
|
146 |
|
147 |
return {
|
148 |
-
"
|
149 |
-
"
|
150 |
}
|
151 |
-
|
152 |
-
# Initialize components
|
153 |
-
product_db = ProductDatabase()
|
154 |
-
price_fetcher = PriceFetcher()
|
155 |
-
recommendation_engine = RecommendationEngine(product_db, price_fetcher)
|
156 |
-
|
157 |
-
def recommend_gifts(text: str) -> Dict:
|
158 |
-
"""Gradio interface function"""
|
159 |
-
if not text:
|
160 |
-
return {"error": "Please provide a description."}
|
161 |
-
|
162 |
-
try:
|
163 |
-
# Get recommendations (using asyncio in a simplified way)
|
164 |
-
import asyncio
|
165 |
-
recommendations = asyncio.run(recommendation_engine.get_recommendations(text))
|
166 |
-
return recommendations
|
167 |
except Exception as e:
|
168 |
return {"error": f"An error occurred: {str(e)}"}
|
169 |
|
@@ -172,14 +62,15 @@ demo = gr.Interface(
|
|
172 |
fn=recommend_gifts,
|
173 |
inputs=gr.Textbox(
|
174 |
lines=3,
|
175 |
-
placeholder="Describe
|
176 |
),
|
177 |
outputs=gr.JSON(),
|
178 |
title="π Smart Gift Recommender",
|
179 |
-
description="Get personalized gift
|
180 |
examples=[
|
|
|
181 |
["age is 25 and he loves puzzle and online FPS games"],
|
182 |
-
["Looking for a gift for my mom who enjoys gardening and cooking"]
|
183 |
]
|
184 |
)
|
185 |
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import pipeline
|
3 |
+
import urllib.parse
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
+
def extract_keywords(text: str, nlp_pipeline) -> list:
|
6 |
+
"""Extract relevant keywords from the input text"""
|
7 |
+
prompt = f"Extract 3-4 most relevant gift-related keywords from: {text}\nKeywords:"
|
8 |
+
response = nlp_pipeline(prompt, max_new_tokens=30, num_return_sequences=1)
|
9 |
+
keywords = response[0]['generated_text'].split('Keywords:')[-1].strip()
|
10 |
+
return [k.strip() for k in keywords.split(',') if k.strip()]
|
11 |
|
12 |
+
def generate_search_urls(keywords: list) -> dict:
|
13 |
+
"""Generate search URLs for various e-commerce platforms"""
|
14 |
+
# Join keywords with appropriate separators for each platform
|
15 |
+
amazon_query = '+'.join(keywords)
|
16 |
+
flipkart_query = ' '.join(keywords)
|
17 |
+
igp_query = '+'.join(keywords)
|
18 |
+
indiamart_query = ' '.join(keywords)
|
19 |
+
|
20 |
+
# Properly encode the queries
|
21 |
+
amazon_query = urllib.parse.quote(amazon_query)
|
22 |
+
flipkart_query = urllib.parse.quote(flipkart_query)
|
23 |
+
igp_query = urllib.parse.quote(igp_query)
|
24 |
+
indiamart_query = urllib.parse.quote(indiamart_query)
|
25 |
+
|
26 |
+
return {
|
27 |
+
"Amazon India": f"https://www.amazon.in/s?k={amazon_query}",
|
28 |
+
"Flipkart": f"https://www.flipkart.com/search?q={flipkart_query}",
|
29 |
+
"IGP Gifts": f"https://www.igp.com/search?q={igp_query}",
|
30 |
+
"IndiaMart": f"https://www.indiamart.com/find?q={indiamart_query}"
|
31 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
+
def recommend_gifts(text: str):
|
34 |
+
"""Main function to generate gift recommendations"""
|
35 |
+
if not text:
|
36 |
+
return {"error": "Please provide a description."}
|
37 |
+
|
38 |
+
try:
|
39 |
+
# Initialize the language model
|
40 |
+
nlp = pipeline(
|
41 |
+
"text-generation",
|
42 |
+
model="gpt2",
|
43 |
+
device_map="auto"
|
44 |
+
)
|
45 |
|
46 |
+
# Extract relevant keywords
|
47 |
+
keywords = extract_keywords(text, nlp)
|
|
|
|
|
|
|
48 |
|
49 |
+
# Generate search URLs
|
50 |
+
search_links = generate_search_urls(keywords)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
return {
|
53 |
+
"keywords": keywords,
|
54 |
+
"search_links": search_links
|
55 |
}
|
56 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
except Exception as e:
|
58 |
return {"error": f"An error occurred: {str(e)}"}
|
59 |
|
|
|
62 |
fn=recommend_gifts,
|
63 |
inputs=gr.Textbox(
|
64 |
lines=3,
|
65 |
+
placeholder="Describe who you're buying a gift for (age, interests, occasion, etc.)"
|
66 |
),
|
67 |
outputs=gr.JSON(),
|
68 |
title="π Smart Gift Recommender",
|
69 |
+
description="Get personalized gift suggestions with direct shopping links!",
|
70 |
examples=[
|
71 |
+
["a small kid of age 3 want him to have something like toy that teaches him alphabets"],
|
72 |
["age is 25 and he loves puzzle and online FPS games"],
|
73 |
+
["Looking for a gift for my mom who enjoys gardening and cooking"]
|
74 |
]
|
75 |
)
|
76 |
|