Sentiment Analysis of Reviews
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
The Sentiment Analysis of Reviews feature is an intelligent system designed to automatically analyze the sentiment of user-submitted product reviews. It leverages an external AI model to process the review text and classify it as positive, negative, or neutral. The primary purpose of this feature is to provide sellers and administrators with valuable insights into customer feedback, enabling them to better understand product reception and improve service quality.
The analysis is performed on the backend and the results are intended for display within the seller and admin dashboards. The system is built using Node.js, Express, and integrates with a Hugging Face Inference API for the natural language processing task.
Sources: README.md, backend/controller/analyzeSentiment.js, backend/controller/product.js
System Architecture
The sentiment analysis process is triggered not upon review submission, but when a seller requests their product list. This design ensures that the user experience of submitting a review is fast, while the processing-intensive analysis is handled asynchronously for the seller's benefit.
The diagram below illustrates the high-level data flow for sentiment analysis.
This diagram shows the two main user flows: a customer submitting a review, and a seller viewing their products with analyzed sentiments.
Sources: backend/controller/product.js:101-147, 235-288, backend/controller/analyzeSentiment.js
Backend Implementation
The backend is responsible for storing reviews, orchestrating the analysis with an external service, and attaching the sentiment data to product information for sellers.
Sources: backend/controller/product.js, backend/controller/analyzeSentiment.js
Review Submission
When a user submits a review, the backend simply stores it in the database without performing any analysis at that time.
| API Endpoint | PUT /api/v2/product/create-new-review |
|---|---|
| Description | Creates a new review or updates an existing one for a product. Requires user authentication. |
| Authentication | isAuthenticated middleware is used. |
Request Body Parameters:
| Parameter | Type | Description |
|---|---|---|
user | Object | The user object of the reviewer. |
rating | Number | The star rating (1-5). |
comment | String | The text content of the review. |
productId | String/Number | The ID of the product being reviewed. |
orderId | String/Number | The ID of the order associated with the purchase. |
The logic checks if the user has already reviewed the product. If so, it updates the existing review; otherwise, it adds a new one. It also recalculates the product's average ratings.
Sources: backend/controller/product.js:235-288
Sentiment Analysis Service
The core analysis is handled by a dedicated module that communicates with a Hugging Face model.
Sources: backend/controller/analyzeSentiment.js
Service Configuration
- API Endpoint:
https://api-inference.huggingface.co/models/finiteautomata/bertweet-base-sentiment-analysis - Authentication: Uses a Bearer token from the environment variable
process.env.HUGGINGFACE_API_TOKEN. - Dependencies:
axiosis used for making HTTP requests.
Sources: backend/controller/analyzeSentiment.js:4, 10, backend/package.json:13
Key Functions
The analyzeSentiment.js module exports several helper functions to manage the analysis process.
| Function | Description |
|---|---|
checkModelStatus() | Sends a GET request to the Hugging Face API to check if the model is currently loading. It returns false if the model is loading, preventing analysis calls until it's ready. |
analyzeSentiment(review) | Sends the review text as a POST request to the Hugging Face API and returns the sentiment result. |
getDominantLabel(result) | Parses the API response (an array of labels with scores) and returns the label with the highest score (e.g., 'POS', 'NEU', 'NEG'). |
Sources: backend/controller/analyzeSentiment.js:6-38
Data Fetching with Sentiment Analysis
Sentiment analysis is performed when a seller requests the list of their own products.
| API Endpoint | GET /api/v2/product/get-all-products-shop/:id |
|---|---|
| Description | Retrieves all products for a specific shop and enriches the review data with sentiment analysis results. |
| Parameters | id (URL parameter): The ID of the shop. |
The following sequence diagram details the process for this endpoint.
Frontend Implementation
On the frontend, the user interacts with the review system by submitting reviews. The analyzed sentiment is not displayed to the general public on the product details page but is intended for the seller's dashboard.
Submitting a Review
A customer can submit a review from their order details page once the order status is "Delivered".
- Component:
UserOrderDetails.jsx - Trigger: A "Reviews" button appears next to each delivered product.
- UI: Clicking the button opens a modal where the user can select a star rating and write a comment.
- Action: The
reviewHandlerfunction is called on submission.
// frontend/src/components/UserOrderDetails.jsx:42-62
const reviewHandler = async (e) => {
await axios
.put(
`${server}/product/create-new-review`,
{
user,
rating,
comment,
productId: selectedItem?.id,
orderId: id,
},
{ withCredentials: true },
)
.then((res) => {
toast.success(res.data.message);
dispatch(getAllOrdersOfUser(user.id));
setComment('');
setRating(null);
setOpen(false);
})
.catch((error) => {
toast.error(error);
});
};
Sources: frontend/src/components/UserOrderDetails.jsx:42-62, 114-122, 186-191
Displaying Reviews (Public View)
The public-facing product details page displays reviews but does not show the analyzed sentiment. It renders the user's name, avatar, star rating, and the raw comment text.
- Component:
ProductDetails.jsx - Functionality: In the "Reviews" tab, the component maps over the
data.reviewsarray to display each review. The sentiment data, although potentially available on other data-fetching routes, is not rendered here.
// frontend/src/components/Products/ProductDetails.jsx:322-337
{activeTab === 2 && (
<div className="space-y-4">
{data?.reviews && data?.reviews?.length > 0 ? (
data.reviews.map((review, index) => (
<div key={index} className="flex space-x-4 bg-gray-100 p-4 rounded-lg shadow-md">
<img
src={`${backend_url}${review.user.avatar}`}
alt="User Avatar"
className="w-12 h-12 rounded-full border"
/>
<div>
<h3 className="font-medium text-lg">{review.user.name}</h3>
<Ratings rating={review.rating} />
<p className="text-gray-700">{review.comment}</p>
</div>
</div>
))
) : (
<p className="text-center text-gray-500">The product has no reviews yet!</p>
)}
</div>
)}
Sources: frontend/src/components/Products/ProductDetails.jsx:322-337
Summary
The sentiment analysis feature is a powerful tool for sellers, providing automated insights from customer feedback. It is implemented on the backend and integrates with the Hugging Face Inference API. The analysis is performed when a seller fetches their product data, enriching each review with a sentiment label and score. While the frontend components for submitting and viewing reviews are in place, the display of the sentiment analysis results is specific to the seller-facing part of the application, aligning with the feature's goal of empowering sellers with actionable data.
Sources: README.md, backend/controller/product.js, backend/controller/analyzeSentiment.js