使用React和Java實現(xiàn)文本摘要小工具
在當今互聯(lián)網(wǎng)時代,GPT、文心一言、通義千問等等模型的不斷興起,互聯(lián)網(wǎng)可能正進入一個AI時代。本文講通過一個小案列來講述我們怎么通過AI給我們的項目、產(chǎn)品等賦能。本文將詳細介紹如何使用 React 和 Java 搭建一個小型文本摘要工具,并基于 Hugging Face 提供的 API 來實現(xiàn)智能摘要功能。從功能分析到代碼實現(xiàn),我們將為你展現(xiàn)一個完整的技術實現(xiàn)過程。
項目目標
我們的目標是構建一個 Web 應用,用戶可以通過簡單的界面輸入文本并快速獲取摘要內容。具體功能包括:
- 文本輸入框: 用戶輸入需要摘要的長文本。
- 摘要展示框: 顯示智能生成的文本摘要。
- 后端 API: 使用 Java 集成 Hugging Face 提供的模型服務。
- 前后端交互: 基于 RESTful API,實現(xiàn)前端請求和后端處理的無縫銜接。
技術棧
前端
- React:用于構建用戶界面。
- Axios:用于發(fā)起 API 請求。
- CSS:簡單樣式美化。
后端
- Spring Boot:用于構建 RESTful 服務。
- Jakarta Validation:用于校驗用戶輸入。
- Hugging Face API:調用預訓練的文本摘要模型。
項目實現(xiàn)
1. 創(chuàng)建后端服務
1.1 項目結構
我們將采用分層架構,將代碼分為以下模塊:
- Controller 層: 處理請求和響應。
- Service 層: 核心業(yè)務邏輯。
- Client 層: 與 AI 模型或外部服務的交互。
- DTO: 用于數(shù)據(jù)傳輸。
- 配置類: 用于定義全局配置,如 API 密鑰等。
目錄結構如下:
backend/
├── src/main/java/com/lucifer/summarizer/
│ ├── config/ # 配置類
│ ├── controller/ # 控制器
│ ├── service/ # 服務層
│ ├── client/ # AI服務交互
│ ├── dto/ # 數(shù)據(jù)傳輸對象
│ ├── exception/ # 異常處理
│ └── SummarizerApplication.java
└── src/main/resources/
├── application.yml # 配置文件
1.2 核心代碼實現(xiàn)
1. 配置文件
application.yml
server: port: 8080 ? huggingface: api-key: your-huggingface-api-key model-url: https://api-inference.huggingface.co/models/facebook/bart-large-cnn
2. 配置類
HuggingFaceConfig.java
package com.lucifer.summarizer.config;
?
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
?
@Configuration
@Getter
public class HuggingFaceConfig {
?
@Value("${huggingface.api-key}")
private String apiKey;
?
@Value("${huggingface.model-url}")
private String modelURL;
}
?
3. 數(shù)據(jù)傳輸對象 (DTO)
TextInputDTO.java
package com.lucifer.summarizer.dto;
?
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
?
import java.io.Serializable;
?
@Data
public class TextInputDTO implements Serializable {
?
@NotBlank(message = "文本不能為空")
private String text;
}
TextOutputDTO.java
package com.lucifer.summarizer.dto;
?
import lombok.AllArgsConstructor;
import lombok.Data;
?
@Data
@AllArgsConstructor
public class TextOutputDTO implements Serializable {
?
private String summary;
}4. 客戶端
HuggingFaceClient.java
package com.lucifer.summarizer.client;
?
import com.lucifer.summarizer.config.HuggingFaceConfig;
import lombok.AllArgsConstructor;
import okhttp3.*;
import org.springframework.stereotype.Component;
?
import java.io.IOException;
?
@Component
@AllArgsConstructor
public class HuggingFaceClient {
?
private final HuggingFaceConfig config;
?
public String getSummary(String text) throws IOException {
OkHttpClient client = new OkHttpClient();
?
RequestBody body = RequestBody.create(
"{"inputs":"" + text + ""}",
MediaType.get("application/json")
);
Request request = new Request.Builder()
.url(config.getModelURL())
.addHeader("Authorization", "Bearer " + config.getApiKey())
.post(body)
.build();
?
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
assert response.body() != null;
return response.body().string();
} else {
throw new IOException("Failed to get summary: " + response.message());
}
}
}
}
?
5. 服務層
SummarizerService.java
package com.lucifer.summarizer.service;
?
public interface SummarizerService {
?
String summarizeText(String text);
}
SummarizerServiceImpl.java
package com.lucifer.summarizer.service.impl;
?
import com.lucifer.summarizer.client.HuggingFaceClient;
import com.lucifer.summarizer.service.SummarizerService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
?
import java.io.IOException;
?
@Service
@AllArgsConstructor
public class SummarizerServiceImpl implements SummarizerService {
?
private final HuggingFaceClient client;
?
@Override
public String summarizeText(String text) {
try {
return client.getSummary(text);
} catch (IOException e) {
throw new RuntimeException("Error while summarizing text", e);
}
}
}6. 控制器
SummarizerController.java
package com.lucifer.summarizer.controller;
?
import com.lucifer.summarizer.dto.TextInputDTO;
import com.lucifer.summarizer.dto.TextOutputDTO;
import com.lucifer.summarizer.service.SummarizerService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;
?
@RestController
@AllArgsConstructor
@RequestMapping("/api/v1")
public class SummarizerController {
?
private final SummarizerService summarizerService;
?
@PostMapping("/summarizer")
public ResponseEntity<TextOutputDTO> summarize(@Valid @RequestBody TextInputDTO input) {
String summary = summarizerService.summarizeText(input.getText());
return ResponseEntity.ok(new TextOutputDTO(summary));
}
}7. 異常處理
package com.lucifer.summarizer.exception;
?
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
?
@ControllerAdvice
public class GlobalExceptionHandler {
?
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error: " + ex.getMessage());
}
?
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error: " + ex.getMessage());
}
}8. 服務啟動

9. 接口測試

2. 創(chuàng)建前端界面
2.1 初始化 React 項目
使用 create-react-app 初始化項目:
npx create-react-app text-summary-app cd text-summary-app
安裝 Axios:
npm install axios
2.2 創(chuàng)建主界面組件
import React, { useState } from "react";
import axios from "axios";
?
const TextSummary = () => {
const [text, setText] = useState("");
const [summary, setSummary] = useState("");
const [loading, setLoading] = useState(false);
?
const handleSubmit = async () => {
if (text.trim().length < 10) {
alert("請輸入至少10個字符的文本!");
return;
}
?
setLoading(true);
try {
const response = await axios.post("/api/v1/summarizer", { text });
setSummary(response.data);
} catch (error) {
alert("請求失敗,請稍后重試!");
} finally {
setLoading(false);
}
};
?
return (
<div style={{ padding: "20px", fontFamily: "Arial, sans-serif" }}>
<h1>AI 文本摘要工具</h1>
<textarea
style={{ width: "100%", height: "150px", marginBottom: "20px" }}
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="輸入需要摘要的文本..."
></textarea>
<button onClick={handleSubmit} disabled={loading}>
{loading ? "處理中..." : "生成摘要"}
</button>
{summary && (
<div style={{ marginTop: "20px", padding: "10px", border: "1px solid #ccc" }}>
<h2>摘要結果:</h2>
<p>{summary}</p>
</div>
)}
</div>
);
};
?
export default TextSummary;
2.3 配置代理(開發(fā)環(huán)境)
在 package.json 中添加代理配置:
"proxy": "http://localhost:9527"
深入優(yōu)化
1.用戶體驗:
- 添加字符計數(shù)器,限制輸入長度。
- 使用第三方組件庫(如 Material-UI)改進界面樣式。
2.性能優(yōu)化:
- 在后端使用緩存(如 Redis)存儲最近的摘要結果。
- 在前端增加延遲請求,減少頻繁調用。
3.錯誤處理:
- 處理 Hugging Face API 的限流問題。
- 提供友好的錯誤提示。
4.擴展功能:
- 支持多語言摘要。
- 添加更多 AI 模型(如情感分析、關鍵詞提取)。
以上就是使用React和Java實現(xiàn)文本摘要小工具的詳細內容,更多關于React Java文本摘要的資料請關注腳本之家其它相關文章!
相關文章
java如何讀取properties文件將參數(shù)值配置到靜態(tài)變量
這篇文章主要介紹了java如何讀取properties文件將參數(shù)值配置到靜態(tài)變量問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
詳解Mybatis攔截器安全加解密MySQL數(shù)據(jù)實戰(zhàn)
本文主要介紹了Mybatis攔截器安全加解密MySQL數(shù)據(jù)實戰(zhàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
Mybatis中SqlSession下的四大對象之執(zhí)行器(executor)
mybatis中sqlsession下的四大對象是指:executor, statementHandler,parameterHandler,resultHandler對象。這篇文章主要介紹了Mybatis中SqlSession下的四大對象之執(zhí)行器(executor),需要的朋友可以參考下2019-04-04
Java找出兩個大數(shù)據(jù)量List集合中的不同元素的方法總結
本文將帶大家了解如何快速的找出兩個相似度非常高的List集合里的不同元素。主要通過Java API、List集合雙層遍歷比較不同、借助Map集合查找三種方式,需要的可以參考一下2022-10-10

