Vedant Nagarkar commited on
Commit
cf56ee3
Β·
1 Parent(s): e34337d

Add pranalyzer Gradio app

Browse files
Files changed (2) hide show
  1. app.py +208 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from transformers import (
4
+ pipeline,
5
+ BartForConditionalGeneration,
6
+ BartTokenizer
7
+ )
8
+
9
+ # ── Device ────────────────────────────────────
10
+ DEVICE = 0 if torch.cuda.is_available() else -1
11
+ DEVICE_STR = "cuda" if torch.cuda.is_available() else "cpu"
12
+
13
+ # ── Categories & Aspects ──────────────────────
14
+ CATEGORIES = [
15
+ "Electronics",
16
+ "Clothing and Fashion",
17
+ "Books and Literature",
18
+ "Food and Grocery",
19
+ "Sports and Outdoors",
20
+ "Home and Kitchen",
21
+ "Beauty and Personal Care",
22
+ "Toys and Games"
23
+ ]
24
+
25
+ ASPECTS = [
26
+ "price and value",
27
+ "quality and durability",
28
+ "delivery and shipping",
29
+ "customer service",
30
+ "ease of use",
31
+ "design and appearance",
32
+ "performance and speed",
33
+ "battery life"
34
+ ]
35
+
36
+ # ── Load all models from HuggingFace Hub ──────
37
+ print("Loading sentiment model...")
38
+ sentiment_pipe = pipeline(
39
+ "text-classification",
40
+ model = "Ved2001/pranalyzer",
41
+ device = DEVICE
42
+ )
43
+
44
+ print("Loading category classifier...")
45
+ category_pipe = pipeline(
46
+ "zero-shot-classification",
47
+ model = "facebook/bart-large-mnli",
48
+ device = DEVICE
49
+ )
50
+
51
+ print("Loading aspect analyzer...")
52
+ aspect_pipe = pipeline(
53
+ "zero-shot-classification",
54
+ model = "cross-encoder/nli-roberta-base",
55
+ device = DEVICE
56
+ )
57
+
58
+ print("Loading summarization model...")
59
+ bart_tokenizer = BartTokenizer.from_pretrained(
60
+ "facebook/bart-large-xsum")
61
+ bart_model = BartForConditionalGeneration\
62
+ .from_pretrained("facebook/bart-large-xsum")\
63
+ .to(DEVICE_STR)
64
+
65
+ print("All models loaded!")
66
+
67
+
68
+ # ── Inference functions ───────────────────────
69
+ def analyze_sentiment(text):
70
+ result = sentiment_pipe(text[:512])[0]
71
+ return {'label': result['label'], 'score': round(result['score'], 4)}
72
+
73
+ def classify_category(text):
74
+ result = category_pipe(
75
+ text[:512],
76
+ candidate_labels=CATEGORIES,
77
+ multi_label=False
78
+ )
79
+ return {'category': result['labels'][0], 'score': round(result['scores'][0], 4)}
80
+
81
+ def analyze_aspects(text):
82
+ result = aspect_pipe(
83
+ text[:512],
84
+ candidate_labels=ASPECTS,
85
+ multi_label=True
86
+ )
87
+ return [
88
+ (label, round(score, 4))
89
+ for label, score in zip(result['labels'], result['scores'])
90
+ if score > 0.3
91
+ ][:3]
92
+
93
+ def summarize_review(text):
94
+ if len(text.split()) < 30:
95
+ return text
96
+ inputs = bart_tokenizer(
97
+ text[:512],
98
+ return_tensors="pt",
99
+ truncation=True,
100
+ max_length=512
101
+ ).to(DEVICE_STR)
102
+ summary_ids = bart_model.generate(
103
+ inputs["input_ids"],
104
+ max_new_tokens=80,
105
+ min_length=15,
106
+ length_penalty=2.0,
107
+ num_beams=4,
108
+ early_stopping=True
109
+ )
110
+ return bart_tokenizer.decode(
111
+ summary_ids[0], skip_special_tokens=True)
112
+
113
+
114
+ # ── Gradio function ───────────────────────────
115
+ def run_analysis(review_text):
116
+ if not review_text.strip():
117
+ return ("Please enter a review!",) * 4
118
+
119
+ sentiment = analyze_sentiment(review_text)
120
+ category = classify_category(review_text)
121
+ aspects = analyze_aspects(review_text)
122
+ summary = summarize_review(review_text)
123
+
124
+ # Format sentiment
125
+ emoji = "😊" if sentiment['label'] == "POSITIVE" else "😞"
126
+ sentiment_out = (
127
+ f"{emoji} {sentiment['label']}\n"
128
+ f"Confidence: {sentiment['score']*100:.1f}%"
129
+ )
130
+
131
+ # Format category
132
+ category_out = (
133
+ f"πŸ“¦ {category['category']}\n"
134
+ f"Confidence: {category['score']*100:.1f}%"
135
+ )
136
+
137
+ # Format aspects
138
+ aspects_out = "πŸ” Aspects Mentioned:\n\n"
139
+ for aspect, score in aspects:
140
+ bar = "β–ˆ" * int(score * 10)
141
+ empty = "β–‘" * (10 - int(score * 10))
142
+ aspects_out += f"β€’ {aspect:<25} {score:.2f} {bar}{empty}\n"
143
+ if not aspects:
144
+ aspects_out += "No strong aspects detected."
145
+
146
+ # Format summary
147
+ summary_out = f"πŸ“ {summary}"
148
+
149
+ return sentiment_out, category_out, aspects_out, summary_out
150
+
151
+
152
+ # ── Gradio UI ─────────────────────────────────
153
+ with gr.Blocks(title="pranalyzer") as demo:
154
+
155
+ gr.Markdown("""
156
+ # πŸ›οΈ pranalyzer
157
+ ### Product Review Analyzer
158
+ Paste any Amazon product review and get instant analysis
159
+ using 4 NLP models running in parallel.
160
+ ---
161
+ """)
162
+
163
+ review_input = gr.Textbox(
164
+ label = "πŸ“ Paste your product review here",
165
+ placeholder = "e.g. This laptop is amazing! Battery lasts all day...",
166
+ lines = 6
167
+ )
168
+
169
+ analyze_btn = gr.Button(
170
+ "πŸ” Analyze Review",
171
+ variant = "primary",
172
+ size = "lg"
173
+ )
174
+
175
+ gr.Markdown("### πŸ“Š Analysis Results")
176
+
177
+ with gr.Row():
178
+ sentiment_out = gr.Textbox(label="😊 Sentiment", lines=3)
179
+ category_out = gr.Textbox(label="πŸ“¦ Category", lines=3)
180
+
181
+ with gr.Row():
182
+ aspects_out = gr.Textbox(label="πŸ” Aspects", lines=6)
183
+ summary_out = gr.Textbox(label="πŸ“ Summary", lines=6)
184
+
185
+ gr.Examples(
186
+ examples=[
187
+ ["This laptop is absolutely incredible! Battery lasts all day, easily 10-12 hours of real work. The display is crisp and bright. Performance is blazing fast. Highly recommended!"],
188
+ ["Complete waste of money. Stopped working after a week. Customer service was useless and refused a refund. Avoid at all costs."],
189
+ ["Ordered these running shoes for marathon training. Delivery was super fast. Cushioning is excellent. Only downside is sizing runs small, order a size up."],
190
+ ["This cookbook is a disappointment. Half the recipes have missing ingredients. Very misleading. Wasted expensive ingredients trying three different recipes."]
191
+ ],
192
+ inputs=review_input
193
+ )
194
+
195
+ gr.Markdown("""
196
+ ---
197
+ **Models:** `DistilBERT` β†’ Sentiment | `BART-MNLI` β†’ Category | `RoBERTa` β†’ Aspects | `BART-XSUM` β†’ Summary
198
+ Built by [Vedant Nagarkar](https://huggingface.co/Ved2001) β€’
199
+ [GitHub](https://github.com/Vedant-Nagarkar/product-review-analyzer)
200
+ """)
201
+
202
+ analyze_btn.click(
203
+ fn = run_analysis,
204
+ inputs = review_input,
205
+ outputs = [sentiment_out, category_out, aspects_out, summary_out]
206
+ )
207
+
208
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers==5.0.0
2
+ torch==2.6.0
3
+ gradio==5.50.0
4
+ datasets==4.0.0
5
+ accelerate==1.13.0
6
+ sentencepiece==0.2.1
7
+ huggingface_hub==1.0.0
8
+ evaluate==0.4.6
9
+ scikit-learn==1.6.1
10
+ numpy==1.26.4