Lakshmi26 commited on
Commit
31ee33b
Β·
1 Parent(s): ca8beb9

Updated app.py with new sentiment analysis code

Browse files
Files changed (3) hide show
  1. README.md +96 -1
  2. app.py +38 -48
  3. requirements.txt +3 -3
README.md CHANGED
@@ -11,4 +11,99 @@ license: apache-2.0
11
  short_description: Sentiment Analysis of reviews using Hugging Face Transformer
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  short_description: Sentiment Analysis of reviews using Hugging Face Transformer
12
  ---
13
 
14
+ # πŸ“ Multi-Domain Sentiment Analysis
15
+
16
+ This project is a **Multi-Domain Sentiment Analysis Application** built using [Gradio](https://www.gradio.app/) and [Hugging Face Transformers](https://huggingface.co/transformers/).
17
+ It allows users to analyze the sentiment of reviews across different domains, such as:
18
+
19
+ - **General Reviews**
20
+ - **Product Reviews**
21
+ - **Movie Reviews**
22
+ - **Food/Restaurant Reviews**
23
+
24
+ The app predicts whether the sentiment is **Positive** or **Negative** and shows the confidence score.
25
+
26
+ ---
27
+
28
+ ## πŸš€ Features
29
+ - 🌐 **Multi-domain support** (General, Products, Movies, Food/Restaurant).
30
+ - πŸ€— **Pretrained models from Hugging Face Hub** for accurate sentiment classification.
31
+ - 🎯 **Confidence Score** included with each prediction.
32
+ - πŸ’‘ **User-friendly Gradio Interface** with dropdowns and text inputs.
33
+ - ⚑ **Runs directly in Hugging Face Spaces** β€” no local setup required.
34
+
35
+ ---
36
+
37
+ ## 🧠 Models Used
38
+
39
+ Each domain uses a domain-specific model from Hugging Face Hub:
40
+
41
+ | Domain | Model Name | Task |
42
+ |--------------------|-------------------------------------------------------------------------|-----------------------|
43
+ | General | `distilbert-base-uncased-finetuned-sst-2-english` | Binary Sentiment |
44
+ | Product Reviews | `nlptown/bert-base-multilingual-uncased-sentiment` | Star Ratings (mapped) |
45
+ | Movie Reviews | `textattack/distilbert-base-uncased-imdb` | Binary Sentiment |
46
+ | Food/Restaurant | `siebert/sentiment-roberta-large-english` | Binary Sentiment |
47
+
48
+ ---
49
+
50
+ ## πŸ“– How It Works
51
+
52
+ 1. Select a **domain** from the dropdown (e.g., *Movie Reviews*).
53
+ 2. Enter a **review** in the text box.
54
+ 3. The app returns:
55
+ - **Domain**
56
+ - **Predicted Sentiment** (Positive/Negative)
57
+ - **Confidence Score**
58
+
59
+ ### Example:
60
+
61
+ Domain: Food/Restaurant
62
+ Sentiment: Negative
63
+ Confidence: 99.95%
64
+
65
+
66
+ ---
67
+
68
+ ## πŸ› οΈ Installation (Optional: For local testing)
69
+
70
+ If you want to run this project locally:
71
+
72
+ ```bash
73
+ # Clone the repository
74
+ git clone https://huggingface.co/spaces/<your-username>/multi_domain_reviews_sentiment
75
+ cd multi_domain_reviews_sentiment
76
+
77
+ # Install dependencies
78
+ pip install -r requirements.txt
79
+
80
+ # Run the app
81
+ python app.py
82
+
83
+
84
+ ---
85
+
86
+ ## πŸ“¦ Requirements
87
+
88
+ The main dependencies are:
89
+
90
+ - `transformers`
91
+ - `torch`
92
+ - `gradio`
93
+
94
+ All dependencies are listed in **`requirements.txt`**.
95
+
96
+ ---
97
+
98
+ ## πŸ™Œ Acknowledgements
99
+
100
+ - πŸ€— **Hugging Face** β€” for models and hosting.
101
+ - 🎨 **Gradio** β€” for the simple and elegant UI.
102
+ - Pretrained models:
103
+ - DistilBERT
104
+ - NLPTown BERT
105
+ - IMDB DistilBERT
106
+ - RoBERTa (Siebert)
107
+
108
+
109
+
app.py CHANGED
@@ -1,56 +1,46 @@
1
- # ===============================
2
- # Sentiment Analysis Web App
3
- # Using Hugging Face Transformers + Gradio
4
- # ===============================
5
 
6
- # Import necessary libraries
7
- import gradio as gr # For building the web UI
8
- from transformers import pipeline # For loading pre-trained NLP models
 
 
 
 
9
 
10
- # -------------------------------
11
- # Step 1: Load Sentiment Model
12
- # -------------------------------
13
- # The pipeline function automatically:
14
- # - Loads a pre-trained model (by default: distilbert-base-uncased-finetuned-sst-2-english)
15
- # - Loads its tokenizer
16
- # - Prepares it for inference
17
- classifier = pipeline("sentiment-analysis")
18
 
19
- # -------------------------------
20
- # Step 2: Define Prediction Function
21
- # -------------------------------
22
- # This function takes a user input (product review text),
23
- # runs it through the classifier, and formats the output.
24
- def analyze_sentiment(review):
25
- # classifier(review) β†’ returns a list of results (one dict per input string).
26
- # Example: [{'label': 'POSITIVE', 'score': 0.9985}]
27
- result = classifier(review)[0] # [0] because we only pass one review at a time.
28
 
29
- # Format output string with:
30
- # - Sentiment label (POSITIVE/NEGATIVE)
31
- # - Confidence score (rounded to 2 decimal places using .2f)
32
- return f"Sentiment: {result['label']} (score: {result['score']:.2f})"
 
33
 
34
- # -------------------------------
35
- # Step 3: Build Gradio Interface
36
- # -------------------------------
37
- # Gr.Interface() connects:
38
- # - fn β†’ the function to call (our analyze_sentiment function)
39
- # - inputs β†’ UI element for user input (Textbox for review text)
40
- # - outputs β†’ UI element for showing results (plain text)
41
- iface = gr.Interface(
42
  fn=analyze_sentiment,
43
- inputs=gr.Textbox(
44
- lines=3, # Multi-line textbox (3 lines height)
45
- placeholder="Enter a product review here..." # Hint text for users
46
- ),
47
- outputs="text" # Output will be shown as plain text
 
 
 
 
48
  )
49
 
50
- # -------------------------------
51
- # Step 4: Launch the Web App
52
- # -------------------------------
53
- # iface.launch() starts a local web server and
54
- # provides a shareable link (optional) to access the app.
55
- iface.launch()
56
-
 
1
+ import gradio as gr
2
+ from transformers import pipeline
 
 
3
 
4
+ # Load domain-specific sentiment pipelines
5
+ models={
6
+ "General":pipeline("sentiment-analysis",model="distilbert-base-uncased-finetuned-sst-2-english"),
7
+ "Product Reviews":pipeline("sentiment-analysis",model="nlptown/bert-base-multilingual-uncased-sentiment"),
8
+ "Movie Reviews":pipeline("sentiment-analysis",model="textattack/distilbert-base-uncased-imdb"),
9
+ "Food/Restaurent":pipeline("sentiment-analysis",model="siebert/sentiment-roberta-large-english"),
10
+ }
11
 
12
+ # Add label mapping for IMDB model (Movie Reviews)
13
+ imdb_label_map={
14
+ "LABEL_0":"Negative",
15
+ "LABEL_1":"Positive"
16
+ }
 
 
 
17
 
18
+ # Define sentiment analysis function
19
+ def analyze_sentiment(domain,review):
20
+ if not review.strip():
21
+ return "Please enter a review."
22
+ clf=models[domain]
23
+ result=clf(review)[0]
 
 
 
24
 
25
+ # Apply mapping only for Movie Reviews domain as it labesl as LABEL_0 and LABEL_1
26
+ if domain=="Movie Reviews":
27
+ result['label']=imdb_label_map[result['label']]
28
+
29
+ return f"Model: {domain}\n\nLabel: {result['label']}\n\nConfidence: {result['score']:.2f}"
30
 
31
+ # Create Gradio interface
32
+ iface=gr.Interface(
 
 
 
 
 
 
33
  fn=analyze_sentiment,
34
+ inputs=[
35
+ gr.Dropdown(list(models.keys()),label="Choose Domain",value="General"),
36
+ gr.Textbox(lines=4,placeholder="Type a review....",label="Review"),
37
+ ],
38
+ outputs=gr.Textbox(label="Prediction"),
39
+ title="Multi-Domain Sentiment Analysis",
40
+ description="Pic a domian and analyze sentiment.",
41
+ allow_flagging="never",
42
+
43
  )
44
 
45
+ # Launch the interface
46
+ iface.launch()
 
 
 
 
 
requirements.txt CHANGED
@@ -1,3 +1,3 @@
1
- transformers
2
- torch
3
- gradio
 
1
+ gradio==5.44.1
2
+ transformers==4.44.2
3
+ torch==2.3.0