使用React和Java實(shí)現(xiàn)文本摘要小工具
在當(dāng)今互聯(lián)網(wǎng)時(shí)代,GPT、文心一言、通義千問等等模型的不斷興起,互聯(lián)網(wǎng)可能正進(jìn)入一個(gè)AI時(shí)代。本文講通過一個(gè)小案列來講述我們?cè)趺赐ㄟ^AI給我們的項(xiàng)目、產(chǎn)品等賦能。本文將詳細(xì)介紹如何使用 React 和 Java 搭建一個(gè)小型文本摘要工具,并基于 Hugging Face 提供的 API 來實(shí)現(xiàn)智能摘要功能。從功能分析到代碼實(shí)現(xiàn),我們將為你展現(xiàn)一個(gè)完整的技術(shù)實(shí)現(xiàn)過程。
項(xiàng)目目標(biāo)
我們的目標(biāo)是構(gòu)建一個(gè) Web 應(yīng)用,用戶可以通過簡(jiǎn)單的界面輸入文本并快速獲取摘要內(nèi)容。具體功能包括:
- 文本輸入框: 用戶輸入需要摘要的長(zhǎng)文本。
- 摘要展示框: 顯示智能生成的文本摘要。
- 后端 API: 使用 Java 集成 Hugging Face 提供的模型服務(wù)。
- 前后端交互: 基于 RESTful API,實(shí)現(xiàn)前端請(qǐng)求和后端處理的無縫銜接。
技術(shù)棧
前端
- React:用于構(gòu)建用戶界面。
- Axios:用于發(fā)起 API 請(qǐng)求。
- CSS:簡(jiǎn)單樣式美化。
后端
- Spring Boot:用于構(gòu)建 RESTful 服務(wù)。
- Jakarta Validation:用于校驗(yàn)用戶輸入。
- Hugging Face API:調(diào)用預(yù)訓(xùn)練的文本摘要模型。
項(xiàng)目實(shí)現(xiàn)
1. 創(chuàng)建后端服務(wù)
1.1 項(xiàng)目結(jié)構(gòu)
我們將采用分層架構(gòu),將代碼分為以下模塊:
- Controller 層: 處理請(qǐng)求和響應(yīng)。
- Service 層: 核心業(yè)務(wù)邏輯。
- Client 層: 與 AI 模型或外部服務(wù)的交互。
- DTO: 用于數(shù)據(jù)傳輸。
- 配置類: 用于定義全局配置,如 API 密鑰等。
目錄結(jié)構(gòu)如下:
backend/
├── src/main/java/com/lucifer/summarizer/
│ ├── config/ # 配置類
│ ├── controller/ # 控制器
│ ├── service/ # 服務(wù)層
│ ├── client/ # AI服務(wù)交互
│ ├── dto/ # 數(shù)據(jù)傳輸對(duì)象
│ ├── exception/ # 異常處理
│ └── SummarizerApplication.java
└── src/main/resources/
├── application.yml # 配置文件
1.2 核心代碼實(shí)現(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ù)傳輸對(duì)象 (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. 服務(wù)層
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. 服務(wù)啟動(dòng)
9. 接口測(cè)試
2. 創(chuàng)建前端界面
2.1 初始化 React 項(xiàng)目
使用 create-react-app 初始化項(xiàng)目:
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("請(qǐng)輸入至少10個(gè)字符的文本!"); return; } ? setLoading(true); try { const response = await axios.post("/api/v1/summarizer", { text }); setSummary(response.data); } catch (error) { alert("請(qǐng)求失敗,請(qǐng)稍后重試!"); } 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>摘要結(jié)果:</h2> <p>{summary}</p> </div> )} </div> ); }; ? export default TextSummary;
2.3 配置代理(開發(fā)環(huán)境)
在 package.json 中添加代理配置:
"proxy": "http://localhost:9527"
深入優(yōu)化
1.用戶體驗(yàn):
- 添加字符計(jì)數(shù)器,限制輸入長(zhǎng)度。
- 使用第三方組件庫(如 Material-UI)改進(jìn)界面樣式。
2.性能優(yōu)化:
- 在后端使用緩存(如 Redis)存儲(chǔ)最近的摘要結(jié)果。
- 在前端增加延遲請(qǐng)求,減少頻繁調(diào)用。
3.錯(cuò)誤處理:
- 處理 Hugging Face API 的限流問題。
- 提供友好的錯(cuò)誤提示。
4.擴(kuò)展功能:
- 支持多語言摘要。
- 添加更多 AI 模型(如情感分析、關(guān)鍵詞提?。?。
以上就是使用React和Java實(shí)現(xiàn)文本摘要小工具的詳細(xì)內(nèi)容,更多關(guān)于React Java文本摘要的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java doGet, doPost方法和文件上傳實(shí)例代碼
這篇文章主要介紹了Java doGet, doPost方法和文件上傳實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-11-11java如何讀取properties文件將參數(shù)值配置到靜態(tài)變量
這篇文章主要介紹了java如何讀取properties文件將參數(shù)值配置到靜態(tài)變量問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08詳解Mybatis攔截器安全加解密MySQL數(shù)據(jù)實(shí)戰(zhàn)
本文主要介紹了Mybatis攔截器安全加解密MySQL數(shù)據(jù)實(shí)戰(zhàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01Java如何使用spire進(jìn)行word文檔的替換詳解
創(chuàng)作一份文案經(jīng)常會(huì)高頻率地使用某些詞匯,如地名、人名、人物職位等,若表述有誤,就需要整體撤換,下面這篇文章主要給大家介紹了關(guān)于Java如何使用spire進(jìn)行word文檔的替換的相關(guān)資料,需要的朋友可以參考下2023-01-01Mybatis中SqlSession下的四大對(duì)象之執(zhí)行器(executor)
mybatis中sqlsession下的四大對(duì)象是指:executor, statementHandler,parameterHandler,resultHandler對(duì)象。這篇文章主要介紹了Mybatis中SqlSession下的四大對(duì)象之執(zhí)行器(executor),需要的朋友可以參考下2019-04-04Java找出兩個(gè)大數(shù)據(jù)量List集合中的不同元素的方法總結(jié)
本文將帶大家了解如何快速的找出兩個(gè)相似度非常高的List集合里的不同元素。主要通過Java API、List集合雙層遍歷比較不同、借助Map集合查找三種方式,需要的可以參考一下2022-10-10