-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproduct_search_cli.py
More file actions
106 lines (82 loc) · 3.92 KB
/
product_search_cli.py
File metadata and controls
106 lines (82 loc) · 3.92 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
"""
Product Search CLI
Allows searching for product sentiment using the backend API
"""
import requests
API_URL = "http://localhost:5000/analyze"
def search_product(product_name, max_items=100):
"""Search for product sentiment using the backend API"""
print("="*70)
print(f"[SEARCH] Searching for product: {product_name}")
print("="*70)
print("\n[INFO] This may take 30-60 seconds to collect and analyze Reddit data...")
try:
response = requests.post(API_URL, json={
"product_name": product_name,
"max_items": max_items,
"time_window": 30,
"subreddits": ["all"],
"min_score": 2
}, timeout=180)
if response.status_code == 200:
data = response.json()
if not data.get('success'):
print(f"\n[ERROR] Analysis failed: {data.get('error', 'Unknown error')}")
return
# Display results
analysis = data.get('analysis', {})
summary = analysis.get('summary', {})
dist = summary.get('overall_sentiment_distribution', {})
print("\n" + "="*70)
print("[SUCCESS] ANALYSIS COMPLETE")
print("="*70)
print(f"\n[PRODUCT] {data['product']}")
print(f"\n[SAMPLE SIZE] {analysis.get('meta', {}).get('sample_size', 0)} items analyzed")
total = dist.get('positive', 0) + dist.get('neutral', 0) + dist.get('negative', 0)
if total > 0:
print(f"\n[SENTIMENT DISTRIBUTION]")
print(f" Positive: {dist.get('positive', 0)} ({dist.get('positive', 0)/total*100:.1f}%)")
print(f" Neutral: {dist.get('neutral', 0)} ({dist.get('neutral', 0)/total*100:.1f}%)")
print(f" Negative: {dist.get('negative', 0)} ({dist.get('negative', 0)/total*100:.1f}%)")
print(f" Avg Score: {summary.get('avg_sentiment_score', 0):.3f}")
if summary.get('themes'):
print(f"\n[TOP THEMES]")
for theme in summary['themes'][:5]:
print(f" - {theme['name']}: {theme['volume']} mentions")
print(f"\n[EXECUTIVE SUMMARY]")
print("-"*70)
print(data.get('narrative', 'No narrative available'))
print("-"*70)
print(f"\n[SAVED TO] {data.get('saved_to', 'N/A')}")
print("="*70 + "\n")
elif response.status_code == 404:
print(f"\n[ERROR] No data found for '{product_name}'")
print("[TIP] Try:")
print(" - Using a shorter product name")
print(" - Checking if the product has Reddit discussions")
print(" - Increasing max_items or time_window")
else:
error_msg = response.json().get('error', 'Unknown error')
print(f"\n[ERROR] {error_msg}")
except requests.exceptions.Timeout:
print("\n[ERROR] Request timed out. The analysis is taking too long.")
print("[TIP] Try reducing max_items or check your internet connection.")
except requests.exceptions.ConnectionError:
print("\n[ERROR] Cannot connect to backend API.")
print("[TIP] Make sure the backend server is running:")
print(" python start_backend.py")
except Exception as e:
print(f"\n[ERROR] Unexpected error: {e}")
import traceback
traceback.print_exc()
def main():
"""Main function to run the CLI"""
print("\nWelcome to the Product Search CLI!")
print("Enter the product name you want to search for.")
while True:
product_name = input("\nEnter product name (or 'exit' to quit): ").strip()
if product_name.lower() == 'exit':
break
search_product(product_name)
if __name__ == '__main__':
main()