THeaxxxxxxxx commited on
Commit
c80675e
·
verified ·
1 Parent(s): 67c436d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -111
app.py CHANGED
@@ -1,130 +1,118 @@
1
  import streamlit as st
 
2
  import torch
3
- from transformers import pipeline
4
- import textwrap
5
 
6
- # Page configuration
7
  st.set_page_config(
8
- page_title="Bank Review Analyzer",
9
- page_icon="🏦",
10
  layout="centered"
11
  )
12
 
13
- # Custom CSS styling
14
- st.markdown("""
15
- <style>
16
- .analysis-section {
17
- padding: 1.5rem;
18
- margin: 1rem 0;
19
- }
20
- .response-box {
21
- background-color: #F8FAFC;
22
- padding: 1.5rem;
23
- border-radius: 0.5rem;
24
- margin: 1rem 0;
25
- }
26
- </style>
27
- """, unsafe_allow_html=True)
28
 
 
29
  @st.cache_resource
30
- def load_models():
31
- """Load ML models"""
32
- with st.spinner("🚀 Loading AI models..."):
33
- device = 0 if torch.cuda.is_available() else -1
34
-
35
- classifier = pipeline(
36
- "zero-shot-classification",
37
- model="MoritzLaurer/deberta-v3-base-zeroshot-v1",
38
- device=device,
39
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
40
- )
41
-
42
- sentiment_analyzer = pipeline(
43
- "sentiment-analysis",
44
- model="cardiffnlp/twitter-roberta-base-sentiment-latest",
45
- device=device
46
- )
47
-
48
- response_generator = pipeline(
49
- "text2text-generation",
50
- model="Leo66277/custom-response-generator",
51
- device=device
52
- )
53
-
54
- return classifier, sentiment_analyzer, response_generator
55
-
56
- def analyze_review(text, models):
57
- """Analysis pipeline"""
58
- classifier, sentiment_analyzer, response_generator = models
59
 
60
- # Topic classification
61
- topics = ["customer service", "mobile app", "credit card", "account security"]
62
- topic_result = classifier(text, topics, multi_label=False)
63
- main_topic = topic_result['labels'][0]
64
 
65
- # Sentiment analysis
66
- sentiment_result = sentiment_analyzer(text)[0]
67
- sentiment = "positive" if sentiment_result['label'] in ['POSITIVE', 'positive'] else "negative"
68
-
69
- # Generate response
70
- prompt = f"""Review: {text}
71
- Topic: {main_topic}
72
- Sentiment: {sentiment}
73
- Generate response:"""
74
-
75
- response = response_generator(
76
- prompt,
77
- max_length=300,
78
- num_return_sequences=1,
79
- do_sample=True,
80
- temperature=0.7
81
- )[0]['generated_text'].strip()
82
-
83
- return main_topic, sentiment, response
84
-
85
- def main():
86
- st.title("🏦 Bank Review Analysis")
87
 
88
- # Main input
89
- review = st.text_area(
90
- "Enter customer review",
91
- height=150,
92
- placeholder="Paste your bank review here..."
93
  )
94
 
95
- # Load models
96
- models = load_models()
 
 
 
97
 
98
- if st.button("Analyze Review"):
99
- if review.strip():
100
- topic, sentiment, response = analyze_review(review, models)
101
-
102
- # Display results
103
- st.markdown("---")
104
- st.markdown("### Analysis Results")
105
-
106
- # Results columns
107
- col1, col2 = st.columns(2)
108
- with col1:
109
- st.markdown(f"**Detected Topic:** {topic}")
110
- st.markdown(f"**Sentiment:** {sentiment.capitalize()}")
111
 
112
- # Response section
113
- st.markdown("---")
114
- st.markdown("### Suggested Response")
115
- st.markdown(f'<div class="response-box">{textwrap.fill(response, width=80)}</div>',
116
- unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- # Download button
119
- st.download_button(
120
- label="Download Report",
121
- data=f"Topic: {topic}\nSentiment: {sentiment}\n\nResponse:\n{response}",
122
- file_name="review_analysis.txt",
123
- mime="text/plain"
124
- )
125
 
126
- else:
127
- st.warning("Please enter a review to analyze")
 
 
 
 
 
 
 
 
 
 
128
 
129
- if __name__ == "__main__":
130
- main()
 
 
 
 
 
 
1
  import streamlit as st
2
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
3
  import torch
 
 
4
 
 
5
  st.set_page_config(
6
+ page_title="Review Assistant",
7
+ page_icon="📝",
8
  layout="centered"
9
  )
10
 
11
+ st.markdown(
12
+ """
13
+ <h2 style='text-align: center;'>Smart Review Analysis Assistant</h2>
14
+ <p style='text-align: center; color: #888;'>Topic Recognition, Sentiment Analysis, and Auto Reply in One Click</p>
15
+ """,
16
+ unsafe_allow_html=True
17
+ )
 
 
 
 
 
 
 
 
18
 
19
+ # ------- Load Pipelines -------
20
  @st.cache_resource
21
+ def load_pipelines():
22
+ # Topic Classification Model (Zero-shot classification)
23
+ topic_labels = [
24
+ "billing", "account access", "customer service", "loans",
25
+ "fraud", "technical issue", "credit card", "mobile app",
26
+ "branch service", "transaction delay", "account closure", "information error"
27
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ device = 0 if torch.cuda.is_available() else -1
30
+ dtype = torch.float16 if torch.cuda.is_available() else torch.float32
 
 
31
 
32
+ topic_classifier = pipeline(
33
+ "zero-shot-classification",
34
+ model="MoritzLaurer/deberta-v3-base-zeroshot-v1",
35
+ device=device,
36
+ torch_dtype=dtype
37
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ # Sentiment Analysis Model
40
+ sentiment_classifier = pipeline(
41
+ "sentiment-analysis",
42
+ model="cardiffnlp/twitter-roberta-base-sentiment-latest", # Best performing model from notebook
43
+ device=device
44
  )
45
 
46
+ # Reply Generation Model
47
+ model_name = "Leo66277/finetuned-tinyllama-customer-replies" # Using the fine-tuned model in the notebook
48
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
49
+ model = AutoModelForCausalLM.from_pretrained(model_name)
50
+ model.to(device)
51
 
52
+ def generate_reply(text):
53
+ prompt_text = f"Please write a short, polite English customer service reply to the following customer comment:\n{text}"
54
+ inputs = tokenizer(prompt_text, return_tensors="pt", truncation=True, max_length=512).to(device)
55
+
56
+ with torch.no_grad():
57
+ gen_ids = model.generate(
58
+ inputs.input_ids,
59
+ max_length=inputs.input_ids.shape[1] + 120,
60
+ pad_token_id=tokenizer.eos_token_id if tokenizer.eos_token_id else tokenizer.pad_token_id,
61
+ num_beams=3,
62
+ no_repeat_ngram_size=2,
63
+ early_stopping=True
64
+ )
65
 
66
+ reply = tokenizer.decode(gen_ids[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip()
67
+ reply = reply.strip('"').replace('\n', ' ').replace(' ', ' ')
68
+ return reply
69
+
70
+ return topic_classifier, sentiment_classifier, generate_reply, topic_labels
71
+
72
+ topic_pipe, sentiment_pipe, reply_generator, topic_labels = load_pipelines()
73
+
74
+ # ------- Page Layout --------
75
+ st.markdown("### Enter a review and get instant analysis ↓")
76
+ example_review = "The people at the call center are inexperienced and lack proper training. I had to call multiple times to resolve a simple issue."
77
+
78
+ user_review = st.text_area(
79
+ "Please enter or paste a review (e.g.):",
80
+ value=example_review,
81
+ height=120
82
+ )
83
+
84
+ if st.button("Analyze"):
85
+ if not user_review.strip():
86
+ st.warning("Please enter a valid review!")
87
+ else:
88
+ with st.spinner("Analyzing..."):
89
+ # Topic Classification
90
+ topic_result = topic_pipe(user_review, topic_labels, multi_label=False)
91
+ topic = topic_result['labels'][0]
92
+ topic_score = round(topic_result['scores'][0] * 100, 1)
93
 
94
+ # Sentiment Analysis
95
+ sentiment_result = sentiment_pipe(user_review)
96
+ sentiment = sentiment_result[0]['label']
97
+ sentiment_score = round(sentiment_result[0]['score'] * 100, 1)
 
 
 
98
 
99
+ # Auto Reply Generation
100
+ reply_text = reply_generator(user_review)
101
+
102
+ # Output Results - card style
103
+ col1, col2 = st.columns(2)
104
+ with col1:
105
+ st.success(f"**Topic:** {topic} ({topic_score}%)")
106
+ with col2:
107
+ st.success(f"**Sentiment:** {sentiment} ({sentiment_score}%)")
108
+
109
+ st.info("**Auto-reply Suggestion:**")
110
+ st.write(f"> {reply_text}")
111
 
112
+ st.markdown(
113
+ """
114
+ <hr/>
115
+ <p style='text-align: center; color: #bbb;'>© 2024 Review AI Assistant</p>
116
+ """,
117
+ unsafe_allow_html=True
118
+ )