-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
321 lines (281 loc) · 10.8 KB
/
Copy pathmain.py
File metadata and controls
321 lines (281 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
from fastapi import FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import List, Optional, Dict
import uvicorn
from dotenv import load_dotenv
import os
from datetime import datetime
# Import custom modules
from src.ner.product_ner import ProductNER
from src.sentiment.sentiment_analyzer import SentimentAnalyzer
from src.search.amazon_search import AmazonSearch
from src.reddit.reddit_scraper import RedditScraper
from src.twitter.twitter_scraper import TwitterScraper
from src.recommendation.recommender import ProductRecommender
# Load environment variables
load_dotenv()
app = FastAPI(
title="Product Analysis and Recommendation API",
description="A REST API for product analysis, sentiment analysis, and recommendations using BERT and various data sources",
version="1.0.0",
docs_url="/api/docs",
redoc_url="/api/redoc"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, replace with specific origins
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Response Models
class SocialMediaComment(BaseModel):
platform: str
author: str
author_name: Optional[str]
text: str
created_at: str
metrics: Dict
url: str
class ProductDiscussion(BaseModel):
platform: str
title: Optional[str]
author: str
score: Optional[int]
created_at: str
url: str
text: str
metrics: Optional[Dict]
comments: Optional[List[SocialMediaComment]]
class ProductRecommendation(BaseModel):
product_name: str
amazon_url: str
sentiment_score: float
social_discussions: List[ProductDiscussion]
confidence_score: float
key_features: List[str]
price: Optional[str]
brand: Optional[str]
image_url: Optional[str]
price_match: bool
feature_match: bool
overall_score: float
class ErrorResponse(BaseModel):
detail: str
status_code: int
timestamp: str
# Request Models
class ProductDescription(BaseModel):
description: str = Field(..., min_length=10, description="Detailed product description")
max_results: Optional[int] = Field(5, ge=1, le=20, description="Maximum number of results to return")
min_sentiment_score: Optional[float] = Field(3.0, ge=1.0, le=5.0, description="Minimum sentiment score for recommendations")
min_confidence_score: Optional[float] = Field(0.6, ge=0.0, le=1.0, description="Minimum confidence score for recommendations")
class HealthCheck(BaseModel):
status: str
version: str
timestamp: str
# Initialize components
ner = ProductNER()
sentiment = SentimentAnalyzer()
amazon = AmazonSearch()
reddit = RedditScraper()
twitter = TwitterScraper()
recommender = ProductRecommender()
@app.get("/api/health", response_model=HealthCheck, tags=["System"])
async def health_check():
"""
Check the health status of the API
"""
return {
"status": "healthy",
"version": "1.0.0",
"timestamp": datetime.utcnow().isoformat()
}
@app.post(
"/api/analyze-product",
response_model=List[ProductRecommendation],
responses={
200: {"description": "Successful analysis"},
400: {"model": ErrorResponse, "description": "Invalid input"},
500: {"model": ErrorResponse, "description": "Internal server error"}
},
tags=["Products"]
)
async def analyze_product(product: ProductDescription):
"""
Analyze a product description and return recommendations with sentiment analysis
- **description**: Detailed product description
- **max_results**: Maximum number of results to return (default: 5, max: 20)
- **min_sentiment_score**: Minimum sentiment score for recommendations (default: 3.0)
- **min_confidence_score**: Minimum confidence score for recommendations (default: 0.6)
Returns a list of product recommendations with sentiment analysis and social media discussions
"""
try:
# Extract product characteristics using NER
characteristics = ner.extract_characteristics(product.description)
# Search for products on Amazon
amazon_products = amazon.search_products(characteristics, max_results=product.max_results)
if not amazon_products:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No products found matching the description"
)
# Get social media discussions and analyze sentiment
recommendations = []
for product in amazon_products:
# Get Reddit discussions
reddit_posts = reddit.search_discussions(product['title'])
# Get Twitter discussions
twitter_posts = twitter.search_tweets(product['title'])
# Combine social media discussions
social_discussions = []
# Process Reddit posts
for post in reddit_posts:
discussion = ProductDiscussion(
platform="reddit",
title=post['title'],
author=post['author'],
score=post['score'],
created_at=post['created_utc'],
url=post['url'],
text=post['selftext'],
comments=[
SocialMediaComment(
platform="reddit",
author=comment['author'],
text=comment['body'],
created_at=comment['created_utc'],
metrics={"score": comment['score']},
url=post['url']
)
for comment in post['comments']
]
)
social_discussions.append(discussion)
# Process Twitter posts
for tweet in twitter_posts:
discussion = ProductDiscussion(
platform="twitter",
author=tweet['author'],
author_name=tweet['author_name'],
created_at=tweet['created_at'],
url=tweet['url'],
text=tweet['text'],
metrics=tweet['metrics']
)
social_discussions.append(discussion)
# Analyze sentiment across all social media discussions
all_texts = [d.text for d in social_discussions]
sentiment_scores = sentiment.analyze_sentiment(all_texts)
# Generate recommendation
recommendation = recommender.generate_recommendation(
product=product,
social_discussions=social_discussions,
sentiment_scores=sentiment_scores,
characteristics=characteristics
)
# Filter recommendations based on minimum scores
if (recommendation['sentiment_score'] >= product.min_sentiment_score and
recommendation['confidence_score'] >= product.min_confidence_score):
recommendations.append(recommendation)
if not recommendations:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No products found meeting the minimum sentiment and confidence scores"
)
return recommendations
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=str(e)
)
@app.get(
"/api/product/{product_id}",
response_model=ProductRecommendation,
responses={
200: {"description": "Product found"},
404: {"model": ErrorResponse, "description": "Product not found"},
500: {"model": ErrorResponse, "description": "Internal server error"}
},
tags=["Products"]
)
async def get_product(product_id: str):
"""
Get detailed information about a specific product by its ID
- **product_id**: The unique identifier of the product
"""
try:
# Search for the specific product
product = amazon.search_products({"PRODUCT": [product_id]}, max_results=1)
if not product:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Product with ID {product_id} not found"
)
# Get social media discussions
reddit_posts = reddit.search_discussions(product[0]['title'])
twitter_posts = twitter.search_tweets(product[0]['title'])
# Combine social media discussions
social_discussions = []
# Process Reddit posts
for post in reddit_posts:
discussion = ProductDiscussion(
platform="reddit",
title=post['title'],
author=post['author'],
score=post['score'],
created_at=post['created_utc'],
url=post['url'],
text=post['selftext'],
comments=[
SocialMediaComment(
platform="reddit",
author=comment['author'],
text=comment['body'],
created_at=comment['created_utc'],
metrics={"score": comment['score']},
url=post['url']
)
for comment in post['comments']
]
)
social_discussions.append(discussion)
# Process Twitter posts
for tweet in twitter_posts:
discussion = ProductDiscussion(
platform="twitter",
author=tweet['author'],
author_name=tweet['author_name'],
created_at=tweet['created_at'],
url=tweet['url'],
text=tweet['text'],
metrics=tweet['metrics']
)
social_discussions.append(discussion)
# Analyze sentiment
all_texts = [d.text for d in social_discussions]
sentiment_scores = sentiment.analyze_sentiment(all_texts)
# Generate recommendation
recommendation = recommender.generate_recommendation(
product=product[0],
social_discussions=social_discussions,
sentiment_scores=sentiment_scores,
characteristics={} # No characteristics needed for specific product lookup
)
return recommendation
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=str(e)
)
if __name__ == "__main__":
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=True,
docs_url="/api/docs",
redoc_url="/api/redoc"
)