在当今互联网时代,gpt、文心一言、通义千问等等模型的不断兴起,互联网可能正进入一个ai时代。本文讲通过一个小案列来讲述我们怎么通过ai给我们的项目、产品等赋能。本文将详细介绍如何使用 react 和 java 搭建一个小型文本摘要工具,并基于 hugging face 提供的 api 来实现智能摘要功能。从功能分析到代码实现,我们将为你展现一个完整的技术实现过程。
项目目标
我们的目标是构建一个 web 应用,用户可以通过简单的界面输入文本并快速获取摘要内容。具体功能包括:
- 文本输入框: 用户输入需要摘要的长文本。
- 摘要展示框: 显示智能生成的文本摘要。
- 后端 api: 使用 java 集成 hugging face 提供的模型服务。
- 前后端交互: 基于 restful api,实现前端请求和后端处理的无缝衔接。
技术栈
前端
- react:用于构建用户界面。
- axios:用于发起 api 请求。
- css:简单样式美化。
后端
- spring boot:用于构建 restful 服务。
- jakarta validation:用于校验用户输入。
- hugging face api:调用预训练的文本摘要模型。
项目实现
1. 创建后端服务
1.1 项目结构
我们将采用分层架构,将代码分为以下模块:
- controller 层: 处理请求和响应。
- service 层: 核心业务逻辑。
- client 层: 与 ai 模型或外部服务的交互。
- dto: 用于数据传输。
- 配置类: 用于定义全局配置,如 api 密钥等。
目录结构如下:
backend/
├── src/main/java/com/lucifer/summarizer/
│ ├── config/ # 配置类
│ ├── controller/ # 控制器
│ ├── service/ # 服务层
│ ├── client/ # ai服务交互
│ ├── dto/ # 数据传输对象
│ ├── exception/ # 异常处理
│ └── summarizerapplication.java
└── src/main/resources/
├── application.yml # 配置文件
1.2 核心代码实现
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. 数据传输对象 (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. 创建前端界面
2.1 初始化 react 项目
使用 create-react-app 初始化项目:
npx create-react-app text-summary-app cd text-summary-app
安装 axios:
npm install axios
2.2 创建主界面组件
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 配置代理(开发环境)
在 package.json 中添加代理配置:
"proxy": "http://localhost:9527"
深入优化
1.用户体验:
- 添加字符计数器,限制输入长度。
- 使用第三方组件库(如 material-ui)改进界面样式。
2.性能优化:
- 在后端使用缓存(如 redis)存储最近的摘要结果。
- 在前端增加延迟请求,减少频繁调用。
3.错误处理:
- 处理 hugging face api 的限流问题。
- 提供友好的错误提示。
4.扩展功能:
- 支持多语言摘要。
- 添加更多 ai 模型(如情感分析、关键词提取)。
以上就是使用react和java实现文本摘要小工具的详细内容,更多关于react java文本摘要的资料请关注代码网其它相关文章!
发表评论