Sentiment Analysis Using Hugging Face API in Spring Boot
In this post, we'll demonstrate how to perform sentiment analysis using Hugging Face's pre-trained models in a Spring Boot application. The app will expose a simple REST API endpoint where users can submit text, and the API will return whether the sentiment of the text is positive or negative.
๐ฆ Step 1: Maven Dependencies
To get started, we'll add the necessary dependencies to our pom.xml file for Spring Boot and HTTP client support:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
⚡ Step 2: Controller for Sentiment Analysis
In this step, we will create a Spring Boot RestController that will handle the sentiment analysis requests. It will communicate with the Hugging Face API to analyze the text.
package com.example.huggingface;
import org.springframework.web.bind.annotation.*;
import java.net.http.*;
import java.net.URI;
@RestController
@RequestMapping("/api/sentiment")
public class SentimentController {
private static final String HF_TOKEN = "your-huggingface-api-token";
private static final String MODEL_ID = "distilbert-base-uncased-finetuned-sst-2-english"; // Hugging Face model for sentiment analysis
@PostMapping
public String analyzeSentiment(@RequestBody String text) throws Exception {
String requestBody = "{ \"inputs\": \"" + text.replace("\"", "\\\"") + "\" }";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api-inference.huggingface.co/models/" + MODEL_ID))
.header("Authorization", "Bearer " + HF_TOKEN)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
}
}
๐ Hugging Face Model Selection
For sentiment analysis, we’re using the distilbert-base-uncased-finetuned-sst-2-english model from Hugging Face. This model is fine-tuned specifically for sentiment analysis (positive or negative) on the SST-2 dataset, but you can choose other models if needed.
๐งช Step 3: Writing the Test Case
Let's write a simple JUnit test to ensure our sentiment analysis API works correctly.
package com.example.huggingface;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SentimentControllerTest {
@Test
void testSentimentAnalysis() {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/api/sentiment";
String text = "I love using Hugging Face models! They are amazing!";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(text, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response.getBody().toLowerCase().contains("positive"));
}
}
๐ Sample Response
When you send a request with the text "I love using Hugging Face models! They are amazing!", you should get a response indicating that the sentiment is positive:
[
{
"label": "POSITIVE",
"score": 0.9998547439575195
}
]
๐ก Tips for Improvement
- Use the Hugging Face API’s
multi-classclassification for more nuanced sentiment analysis (e.g., Happy, Sad, Angry, etc.) - Store your API token in a secure location (like environment variables or Spring's
application.yml) - Use
WebClientin Spring for asynchronous requests if the model takes longer than usual to respond
๐ Conclusion
By following this tutorial, you've successfully built a Spring Boot API that integrates with Hugging Face's powerful NLP models for sentiment analysis. This could easily be expanded to classify text sentiment in real-world applications like reviews, social media, or customer feedback.
Feel free to explore Hugging Face's library for other models suited to your needs!
Comments
Post a Comment