noddysnots commited on
Commit
fcfc0c6
Β·
verified Β·
1 Parent(s): 9d53a42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -47
app.py CHANGED
@@ -1,59 +1,171 @@
1
  import gradio as gr
2
- from transformers import pipeline
3
  import requests
 
 
 
 
 
 
 
4
 
5
- def extract_interests(text):
6
- """Extract interests using a smaller, more efficient model"""
7
- try:
8
- # Using GPT-2 small model which is more lightweight
9
- classifier = pipeline(
10
- "text-generation",
11
- model="gpt2",
12
- max_length=50,
13
- device_map="auto"
14
- )
15
-
16
- prompt = f"List 3 interests from: {text}\nInterests:"
17
- response = classifier(prompt, max_new_tokens=30, num_return_sequences=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- # Clean up the response
20
- interests = response[0]['generated_text'].split('Interests:')[-1].strip()
21
- return [i.strip() for i in interests.split(',') if i.strip()][:3]
22
- except Exception as e:
23
- print(f"Error in extraction: {str(e)}")
24
- return ["general gifts"]
 
 
 
 
 
 
 
 
25
 
26
- def search_gifts(interests):
27
- """Generate shopping links based on interests"""
28
- query = "+".join(interests)
29
- return {
30
- "Amazon India": f"https://www.amazon.in/s?k={query}",
31
- "Flipkart": f"https://www.flipkart.com/search?q={query}",
32
- "IGP Gifts": f"https://www.igp.com/search?q={query}"
33
- }
 
 
 
 
 
 
34
 
35
- def recommend_gifts(text):
36
- """Main recommendation function"""
37
- if not text:
38
- return {
39
- "error": "Please enter a description."
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
-
42
- try:
43
- # Extract interests
44
- interests = extract_interests(text)
45
 
46
- # Get shopping links
47
- links = search_gifts(interests)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  return {
50
- "Identified Interests": interests,
51
- "Shopping Links": links
52
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  except Exception as e:
54
- return {
55
- "error": f"An error occurred: {str(e)}"
56
- }
57
 
58
  # Create Gradio interface
59
  demo = gr.Interface(
@@ -63,10 +175,10 @@ demo = gr.Interface(
63
  placeholder="Describe the person you're buying a gift for (their interests, hobbies, age, occasion, etc.)"
64
  ),
65
  outputs=gr.JSON(),
66
- title="🎁 AI Gift Recommender",
67
- description="Enter details about the person you're buying a gift for, and get personalized suggestions with shopping links!",
68
  examples=[
69
- ["My friend is a 25-year-old software developer who loves gaming and anime"],
70
  ["Looking for a gift for my mom who enjoys gardening and cooking"],
71
  ]
72
  )
 
1
  import gradio as gr
 
2
  import requests
3
+ from bs4 import BeautifulSoup
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
+ class ProductDatabase:
12
+ """Simple in-memory product database with caching"""
13
+ def __init__(self):
14
+ self.products = self._load_initial_products()
15
+ self.price_cache = {}
16
+ self.cache_timeout = 3600 # 1 hour cache timeout
17
+
18
+ def _load_initial_products(self) -> Dict:
19
+ """Load initial product database"""
20
+ return {
21
+ "gaming": [
22
+ {
23
+ "id": "g1",
24
+ "name": "Razer DeathAdder Essential Gaming Mouse",
25
+ "base_price": 1999,
26
+ "category": ["gaming", "accessories"],
27
+ "keywords": ["fps", "gaming", "mouse"],
28
+ "urls": {
29
+ "amazon": "B07F2GC4S9",
30
+ "flipkart": "ACCEYJY6GZGFDW8T"
31
+ }
32
+ },
33
+ # Add more gaming products...
34
+ ],
35
+ "puzzles": [
36
+ {
37
+ "id": "p1",
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
+ async def get_recommendations(self, text: str) -> Dict:
116
+ """Get personalized recommendations based on user input"""
117
+ keywords = self.extract_keywords(text)
118
+ recommendations = []
119
+
120
+ # Get relevant products based on keywords
121
+ for keyword in keywords:
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
+ # Fetch real-time prices and format recommendations
127
+ formatted_recommendations = []
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
+ "recommendations": formatted_recommendations,
149
+ "last_updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
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
 
170
  # Create Gradio interface
171
  demo = gr.Interface(
 
175
  placeholder="Describe the person you're buying a gift for (their interests, hobbies, age, occasion, etc.)"
176
  ),
177
  outputs=gr.JSON(),
178
+ title="🎁 Smart Gift Recommender",
179
+ description="Get personalized gift recommendations with real-time prices!",
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
  )