Spaces:
Sleeping

File size: 4,154 Bytes
77f45ac
3caacc9
1068dc3
3caacc9
 
 
 
 
 
 
 
315bdfb
e20ca0b
3caacc9
015e936
 
 
d155ec2
 
 
 
3caacc9
e20ca0b
f1d8459
e20ca0b
3caacc9
77f45ac
e20ca0b
f1d8459
e20ca0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1d8459
e20ca0b
 
 
4e5313b
e20ca0b
 
1068dc3
 
30758f4
1068dc3
 
 
e20ca0b
1068dc3
54c9dd2
 
e20ca0b
f1d8459
e20ca0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
from transformers import pipeline, AutoTokenizer
from collections import Counter
import re

# Use Finetuned model as classifier of the text
model_id = "SoniaD/CustomModel_Uber"  
classifier = pipeline("text-classification", model=model_id, tokenizer=model_id)

# Load a pre-trained summarization model for extracting key problems from complaints
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
zero_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")

# Load tokenizer separately for token count check
tokenizer = AutoTokenizer.from_pretrained("SoniaD/CustomModel_Uber")

# Clean the text uploaded
def clean_text(text):
    return re.sub(r'\s+', ' ', str(text)).strip()

# Check if the required column 'text' exists
def analyze_reviews(uploaded_file):
    df = pd.read_excel(uploaded_file)
    # Error files
    if 'text' not in df.columns:
        st.error("❌ Error: Your file must contain a column named 'text'.")
        return
        
    # Create a column contains cleaned text
    df["text_clean"] = df["text"].apply(clean_text)
    results = df["text_clean"].apply(lambda x: classifier(x)[0])
    
    # Extract label (Complaint or Not Complaint) and score (confidence)
    df["label"] = results.apply(lambda r: r["label"])
    df["score"] = results.apply(lambda r: round(r["score"], 2))
    
    # Filter only the complaints and sort them by confidence score (descending)
    complaints = df[df["label"] == "Complaint"].sort_values(by="score", ascending=False)
    
    # If no complaints are found, return a positive result
    if complaints.empty:
        st.success("βœ… No complaints found in the uploaded file!")
        return
        
    # Use the summarization model to extract core problem themes
    topic_summary_pairs = []
    complaint_texts = complaints["text_clean"].tolist()
    candidate_labels = ["Driver Issue", "App Issue", "Payment Issue", "Customer Support", "Wait Time"]
    for complaint in complaint_texts:
        try:
            token_len = len(tokenizer(complaint)["input_ids"])
            if token_len > 40:
                summary = summarizer(complaint, max_length=50, min_length=15, do_sample=False)[0]["summary_text"]
            else:
                summary = complaint
            topic_result = zero_classifier(summary, candidate_labels)
            top_topic = topic_result["labels"][0]
            topic_summary_pairs.append((top_topic, summary.strip()))
        except Exception as e:
            st.warning(f"❗ Error processing complaint: {e}")
            continue
            
    # Count how many complaints fall under each topic                
    topic_counts = Counter([pair[0] for pair in topic_summary_pairs])

    # Return the summary text + complaint samples (text only, score hidden)
    st.subheader("🧾 Complaint Summary")
    st.markdown(f"🧾 Total Reviews: {len(df)}\n")
    st.markdown(f"❗ Complaints Detected: {len(complaints)}\n\n")
    st.markdown(f"πŸ“Œ Key Customer Issue Summary (Categorized)")

    # Display categorized summaries sorted by frequency
    for topic, count in topic_counts.most_common():
        st.markdown(f"**πŸ“‚ {topic}** ({count} complaints)")
        for t, s in topic_summary_pairs:
            if t == topic:
                st.markdown(f"- {s}")
                
    st.subheader("πŸ“‹ Complaint Samples")
    st.dataframe(complaints[["text"]].reset_index(drop=True))
    
    # Add download button to export complaints as CSV
    csv_data = complaints[["text"]].to_csv(index=False).encode("utf-8")
    st.download_button(
        label="Download Complaints as CSV",
        data=csv_data,
        file_name="uber_complaints.csv",
        mime="text/csv"
    )
    
# Page Layout
st.set_page_config(page_title="Uber Complaint Detector", layout="wide")
st.title("Uber Complaint Detector")
st.write("Upload an Excel file (.xlsx) with a **`text`** column. This app will identify complaints and summarize key issues.")
uploaded_file = st.file_uploader("Upload Excel File", type=["xlsx"])

if uploaded_file:
    analyze_reviews(uploaded_file)