Spaces:
Sleeping

SoniaD commited on
Commit
3caacc9
·
verified ·
1 Parent(s): 20c4b62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -32
app.py CHANGED
@@ -1,36 +1,65 @@
 
 
1
  import gradio as gr
2
- from transformers import RobertaTokenizer, RobertaForSequenceClassification
3
- import torch
4
-
5
- # Load fine-tuned model and tokenizer
6
- model_path = "./results/checkpoint-25752" # <-- Make sure this path matches your actual checkpoint folder
7
-
8
- # Load tokenizer and model
9
- tokenizer = RobertaTokenizer.from_pretrained(model_path)
10
- model = RobertaForSequenceClassification.from_pretrained(model_path)
11
-
12
- # Inference function: takes two sentences and returns classification
13
- def detect_customer_complaint(premise, hypothesis):
14
- inputs = tokenizer(premise, hypothesis, return_tensors="pt", truncation=True, padding=True, max_length=128)
15
- outputs = model(**inputs)
16
- pred = torch.argmax(outputs.logits, dim=1).item()
17
- return label_map[pred]
18
-
19
- # Assuming label mapping: 0 -> Costumer satisfied", 1 -> Neutral feedback, 2 -> Customer complaint
20
- label_map = {0: "Costumer satisfied", 1: "Neutral feedback", 2: "Customer complaint"}
21
- print("Predicted label:", label_map[predicted_label_idx])
22
-
23
- # Gradio Interface setup
24
- interface = gr.Interface(
25
- fn=detect_customer_complaint,
26
- inputs=[
27
- gr.Textbox(lines=3, placeholder="Enter product description", label="Product Description"),
28
- gr.Textbox(lines=3, placeholder="Enter customer feedback", label="Customer Feedback")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  ],
30
- outputs=gr.Textbox(label="Prediction Result"),
31
- title="Customer Complaint Detector",
32
- description="Enter a product description and a customer feedback. The model will predict whether the feedback is a complaint, neutral, or satisfied."
33
  )
34
 
35
- # Launch the Gradio app
36
- interface.launch()
 
1
+ import pandas as pd
2
+ from transformers import pipeline
3
  import gradio as gr
4
+ from collections import Counter
5
+ import re
6
+
7
+ # Use Finetuned model as classifier of the text
8
+ model_id = "SoniaD/CustomModel_Uber"
9
+ classifier = pipeline("text-classification", model=model_id, tokenizer=model_id)
10
+
11
+ # Load a pre-trained summarization model for extracting key problems from complaints
12
+ problem_extractor = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
13
+
14
+ # Check if the required column 'text' exists
15
+ def analyze_reviews(file):
16
+ df = pd.read_excel(file)
17
+ if 'text' not in df.columns:
18
+ return "❌ Error: Your file must contain a column named 'text'."
19
+
20
+ # Clean the text uploaded
21
+ def clean_text(text):
22
+ return re.sub(r'\s+', ' ', str(text)).strip()
23
+
24
+ # Create a column contains cleaned text
25
+ df["text_clean"] = df["text"].apply(clean_text)
26
+
27
+ results = df["text_clean"].apply(lambda x: classifier(x)[0])
28
+
29
+ # Extract label (Complaint or Not Complaint) and score (confidence)
30
+ df["label"] = results.apply(lambda r: r["label"])
31
+ df["score"] = results.apply(lambda r: round(r["score"], 2))
32
+
33
+ # Filter only the complaints and sort them by confidence score (descending)
34
+ complaints = df[df["label"] == "Complaint"].sort_values(by="score", ascending=False)
35
+
36
+ # If no complaints are found, return a positive result
37
+ if complaints.empty:
38
+ return "✅ No complaints found in the uploaded file!"
39
+
40
+ # Merge all complaint texts into one long string, and split into words
41
+ all_complaints = " ".join(complaints["text_clean"]).split()
42
+
43
+ # Use the summarization model to extract core problem themes
44
+ summary = problem_extractor(all_complaints, max_length=60, min_length=20, do_sample=False)[0]["summary_text"]
45
+
46
+ # Return the summary text + complaint samples (text only, score hidden)
47
+ return (
48
+ f"🧾 Total Reviews: {len(df)}\n"
49
+ f"❗ Complaints Detected: {len(complaints)}\n\n"
50
+ f"📌 Key Customer Issue Summary (from complaints):\n{summary}\n\n",
51
+ complaints[["text"]] # Show only the complaint text without score
52
+ )
53
+
54
+ demo = gr.Interface(
55
+ fn=analyze_reviews,
56
+ inputs=gr.File(label="Upload Excel File (.xlsx)"),
57
+ outputs=[
58
+ gr.Textbox(label="Summary"),
59
+ gr.Dataframe(label="Complaint Samples", wrap=True)
60
  ],
61
+ title="Customer Feedback Analyzer for Uber",
62
+ description="Upload a .xlsx file with a 'text' column. This app will identify complaints and summarize customer issues."
 
63
  )
64
 
65
+ demo.launch()