Skip to content

Commit 4aeda80

Browse files
authored
Merge pull request #13 from adorabled4/feature/interface-extend
新增API , 优化部分旧API代码逻辑
2 parents 3b135b1 + 2f82810 commit 4aeda80

31 files changed

+610
-370
lines changed

api-common/pom.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,12 @@
7272
<artifactId>mybatis-plus-boot-starter</artifactId>
7373
<version>3.5.3</version>
7474
</dependency>
75+
<dependency>
76+
<groupId>com.github.houbb</groupId>
77+
<artifactId>pinyin</artifactId>
78+
<version>0.4.0</version>
79+
<scope>compile</scope>
80+
</dependency>
7581
</dependencies>
7682

7783
<!-- <build> 被依赖的模块不能有这个插件-->
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.dhx.apicommon.model.enums;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.Getter;
5+
6+
/**
7+
* @author adorabled4
8+
* @className LanguageEnum
9+
* @date : 2024/01/14/ 23:32
10+
**/
11+
@Getter
12+
@AllArgsConstructor
13+
public enum LanguageEnum {
14+
CHI("chi_sim"),
15+
ENG("eng");
16+
17+
private final String value ;
18+
19+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.dhx.apicommon.model.v2.param;
2+
3+
import com.dhx.apicommon.model.enums.LanguageEnum;
4+
import lombok.AllArgsConstructor;
5+
import lombok.Builder;
6+
import lombok.Data;
7+
import lombok.NoArgsConstructor;
8+
9+
import javax.validation.constraints.NotNull;
10+
import javax.validation.constraints.Pattern;
11+
import java.io.Serializable;
12+
13+
/**
14+
* @author adorabled4
15+
* @className OCRParam
16+
* @date : 2024/01/14/ 23:26
17+
**/
18+
@Data
19+
@Builder
20+
@AllArgsConstructor
21+
@NoArgsConstructor
22+
public class OCRParam implements Serializable {
23+
24+
private static final long serialVersionUID = 1L;
25+
26+
/**
27+
* base64格式编码的图像文件
28+
*/
29+
@NotNull
30+
private String base64File;
31+
32+
/**
33+
* 需要识别的语言
34+
*/
35+
private LanguageEnum language;
36+
/**
37+
* 图像后缀
38+
*/
39+
@Pattern(regexp = "^(png|jpg|jpeg)$")
40+
private String suffix;
41+
42+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.dhx.apicommon.model.v2.param;
2+
3+
import com.github.houbb.pinyin.constant.enums.PinyinStyleEnum;
4+
import lombok.AllArgsConstructor;
5+
import lombok.Builder;
6+
import lombok.Data;
7+
import lombok.NoArgsConstructor;
8+
import org.hibernate.validator.constraints.Length;
9+
import org.springframework.lang.Nullable;
10+
11+
import java.io.Serializable;
12+
import java.util.List;
13+
14+
/**
15+
* @author adorabled4
16+
* @className PinyinConvertParam
17+
* @date : 2024-1-6 17:34:21
18+
**/
19+
@Data
20+
@Builder
21+
@AllArgsConstructor
22+
@NoArgsConstructor
23+
public class PinyinConvertParam implements Serializable {
24+
25+
private static final long serialVersionUID = 1L;
26+
27+
/**
28+
* 代码
29+
*/
30+
@Length(min = 1, max = 4096, message = "长度非法!")
31+
private String text;
32+
33+
/**
34+
* 类型
35+
*/
36+
private PinyinStyleEnum type;
37+
}

api-core/src/main/java/com/dhx/apicore/util/FileUtil.java renamed to api-common/src/main/java/com/dhx/apicommon/util/FileUtil.java

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
package com.dhx.apicore.util;
1+
package com.dhx.apicommon.util;
22

3+
import cn.hutool.core.util.RandomUtil;
34
import com.dhx.apicommon.common.exception.BusinessException;
45
import com.dhx.apicommon.common.exception.ErrorCode;
56
import org.springframework.web.multipart.MultipartFile;
67

78
import java.io.*;
89
import java.nio.channels.FileChannel;
10+
import java.util.Base64;
911

1012
/**
1113
* @author <a href="https://blog.dhx.icu/"> adorabled4 </a>
@@ -119,8 +121,8 @@ public static String handleCodeTab(String fileName) throws IOException {
119121
}
120122
// 6 chars
121123
// 排除前面的制表符
122-
if(!line.equals("")){
123-
if ( line.charAt(line.length() - 1) == '}' || line.charAt(0) == '}') {
124+
if (!line.equals("")) {
125+
if (line.charAt(line.length() - 1) == '}' || line.charAt(0) == '}') {
124126
tmp.delete(0, 7);
125127
depth--;
126128
}
@@ -141,4 +143,39 @@ public static String handleCodeTab(String fileName) throws IOException {
141143
return handledFile;
142144
}
143145

146+
public static File base64ToFile(String base64File,String suffix) {
147+
FileOutputStream outputStream = null;
148+
try {
149+
Base64.Decoder decoder = Base64.getDecoder();
150+
byte[] decodedBytes = decoder.decode(base64File);
151+
System.out.println(System.getProperty("user.dir"));
152+
// 创建临时文件
153+
File tempFile = new File( "tmp-" + String.valueOf(System.currentTimeMillis() + RandomUtil.randomInt(0, 10000))+"."+suffix);
154+
// 将解码后的数据写入临时文件
155+
outputStream = new FileOutputStream(tempFile);
156+
outputStream.write(decodedBytes);
157+
outputStream.close();
158+
return tempFile; // 返回临时文件对象
159+
} catch (Exception e) {
160+
e.printStackTrace();
161+
}
162+
return null;
163+
}
164+
165+
public static String fileToBase64(String filePath) {
166+
try {
167+
// 创建文件输入流
168+
FileInputStream fileInputStream = new FileInputStream(filePath);
169+
// 读取文件内容为字节数组
170+
byte[] fileContent = new byte[(int) new File(filePath).length()];
171+
fileInputStream.read(fileContent);
172+
fileInputStream.close();
173+
// 对字节数组进行Base64编码
174+
String base64String = Base64.getEncoder().encodeToString(fileContent);
175+
return base64String; // 返回Base64编码后的字符串
176+
} catch (IOException e) {
177+
e.printStackTrace();
178+
return null;
179+
}
180+
}
144181
}

api-core/src/test/java/com/dhx/apicore/service/ApiSDKMultiTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package com.dhx.apicore.service;
22

3-
import com.dhx.apicore.util.FileUtil;
3+
import com.dhx.apicommon.util.FileUtil;
44
import freemarker.cache.ClassTemplateLoader;
55
import freemarker.template.Configuration;
66
import freemarker.template.Template;

api-interface/pom.xml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,18 @@
190190
<scope>test</scope>
191191
</dependency>
192192

193+
<dependency>
194+
<groupId>com.github.houbb</groupId>
195+
<artifactId>pinyin</artifactId>
196+
<version>0.4.0</version>
197+
</dependency>
198+
199+
<!-- https://mvnrepository.com/artifact/net.sourceforge.tess4j/tess4j -->
200+
<dependency>
201+
<groupId>net.sourceforge.tess4j</groupId>
202+
<artifactId>tess4j</artifactId>
203+
<version>5.10.0</version>
204+
</dependency>
193205

194206
</dependencies>
195207

api-interface/src/main/java/com/dhx/apiinterface/ApiInterfaceApplication.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
import org.mybatis.spring.annotation.MapperScan;
55
import org.springframework.boot.SpringApplication;
66
import org.springframework.boot.autoconfigure.SpringBootApplication;
7+
import org.springframework.cache.annotation.EnableCaching;
78
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
89

910
@SpringBootApplication
1011
@MapperScan("com.dhx.apiinterface.mapper")
1112
@EnableDiscoveryClient
1213
@EnableDubbo
14+
@EnableCaching
1315
public class ApiInterfaceApplication {
1416

1517
public static void main(String[] args) {

api-interface/src/main/java/com/dhx/apiinterface/controller/Version1Controller.java

Lines changed: 17 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -54,45 +54,33 @@ public class Version1Controller {
5454

5555
@GetMapping("/suffix")
5656
@Operation(summary = "文件后缀信息查询API")
57-
public BaseResponse<ComputerSuffix> getSuffixDetail(@RequestBody FileSuffixParam param){
58-
QueryWrapper<ComputerSuffix> wrapper = new QueryWrapper<>();
59-
wrapper.eq("suffix",param);
60-
List<ComputerSuffix> list = computerSuffixService.list(wrapper);
61-
if(list==null || list.size()==0){
62-
return ResultUtil.error(ErrorCode.PARAMS_ERROR,"未知的文件后缀~");
57+
public BaseResponse<ComputerSuffix> getSuffixDetail(@RequestBody FileSuffixParam param) {
58+
ComputerSuffix suffix = computerSuffixService.findBySuffix(param);
59+
if (suffix == null) {
60+
return ResultUtil.error(ErrorCode.PARAMS_ERROR, "未知的文件后缀~");
6361
}
64-
return ResultUtil.success(list.get(0));
62+
return ResultUtil.success(suffix);
6563
}
6664

6765

6866
@GetMapping("/lovelorn")
6967
@Operation(summary = "随机失恋文案API")
70-
public BaseResponse<LovelornSentence> getRandomLovelornSentence(){
71-
long total = loveSentenceService.count();
72-
long id = (long) (Math.random()*total+1);
73-
while(id<0 || id >= total){
74-
id = (long) (Math.random()*total+1);
75-
}
76-
// id 不存在, 返回一号
77-
if(loveSentenceService.list(new QueryWrapper<LovelornSentence>().eq("id",id)).size()==0){
78-
return ResultUtil.success(loveSentenceService.getById(1));
79-
}
80-
// 正常返回
81-
return ResultUtil.success(loveSentenceService.getById(id));
68+
public BaseResponse<LovelornSentence> getRandomLovelornSentence() {
69+
Long id = loveSentenceService.randomId();
70+
return ResultUtil.success(loveSentenceService.getSentenceById(id));
8271
}
8372

8473

85-
8674
@GetMapping("/ip/ana")
8775
@Operation(summary = "IPv4属地查询API")
88-
public BaseResponse<String> analysisIP(@RequestBody IpAnaParam param){
89-
try{
76+
public BaseResponse<String> analysisIP(@RequestBody IpAnaParam param) {
77+
try {
9078
InetAddress inetAddress = InetAddress.getByName(param.getIp());
9179
if (inetAddress instanceof Inet4Address) {
9280
String location = IpUtil.getIpLocation(param.getIp());
9381
return ResultUtil.success(location);
9482
} else {
95-
throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数不是合法的IPv4地址!");
83+
throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不是合法的IPv4地址!");
9684
}
9785
} catch (UnknownHostException e) {
9886
throw new RuntimeException(e);
@@ -102,28 +90,25 @@ public BaseResponse<String> analysisIP(@RequestBody IpAnaParam param){
10290

10391
@GetMapping("/ip/me")
10492
@Operation(summary = "获取自身IP属地API")
105-
public BaseResponse<String> getIpOfRequest(HttpServletRequest request){
93+
public BaseResponse<String> getIpOfRequest(HttpServletRequest request) {
10694
String ipAddr = IpUtil.getIpAddr(request);
10795
return ResultUtil.success(ipAddr);
10896
}
10997

11098
@GetMapping("/weather/now")
11199
@Operation(summary = "天气查询API")
112-
public BaseResponse<WeatherInfo> nowWeather(@RequestBody WeatherParam weatherParam, HttpServletRequest request){
113-
if(StringUtils.isEmpty(weatherParam.getCityName())){
100+
public BaseResponse<WeatherInfo> nowWeather(@RequestBody WeatherParam weatherParam, HttpServletRequest request) {
101+
if (StringUtils.isEmpty(weatherParam.getCityName())) {
114102
return weatherService.getWeatherByRequest(request);
115103
}
116104
return weatherService.getWeatherByCityName(weatherParam.getCityName());
117105
}
106+
118107
@GetMapping("/poet/random")
119108
@Operation(summary = "随机诗句API")
120109
public BaseResponse<PoetVO> getRandomPoet() {
121-
long total = poetService.getTotal();
122-
long id = (long) (Math.random() * total + 1);
123-
while (id < 0 || id >= total) {
124-
id = (long) (Math.random() * total + 1);
125-
}
126-
return poetService.getPoetVO(id);
110+
Long id = poetService.randomId();
111+
return ResultUtil.success(poetService.getPoetById(id));
127112
}
128113

129114
}

api-interface/src/main/java/com/dhx/apiinterface/controller/Version2Controller.java

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22

33
import com.dhx.apicommon.common.BaseResponse;
44
import com.dhx.apicommon.common.exception.ErrorCode;
5-
import com.dhx.apicommon.model.v2.param.OJParam;
6-
import com.dhx.apicommon.model.v2.param.TakeCommentParam;
7-
import com.dhx.apicommon.model.v2.param.TranslateParam;
5+
import com.dhx.apicommon.model.v2.param.*;
6+
import com.dhx.apicommon.util.FileUtil;
87
import com.dhx.apicommon.util.ResultUtil;
98
import com.dhx.apicommon.util.ThrowUtil;
109
import com.dhx.apiinterface.manager.AigcManager;
1110
import com.dhx.apiinterface.service.InvokeInterfaceServiceV2;
12-
import com.dhx.apiinterface.service.judge.JavaSandboxTemplate;
1311
import com.dhx.apiinterface.service.judge.JudgeService;
12+
import com.dhx.apiinterface.util.OCRUtil;
13+
import com.github.houbb.pinyin.util.PinyinHelper;
1414
import io.swagger.v3.oas.annotations.Operation;
1515
import io.swagger.v3.oas.annotations.tags.Tag;
1616
import lombok.extern.slf4j.Slf4j;
@@ -20,6 +20,7 @@
2020

2121
import javax.annotation.Resource;
2222
import javax.servlet.http.HttpServletRequest;
23+
import java.io.File;
2324
import java.util.UUID;
2425
import java.util.concurrent.ArrayBlockingQueue;
2526
import java.util.concurrent.ThreadPoolExecutor;
@@ -58,7 +59,7 @@ public BaseResponse genTakeOutComment(@RequestBody @Validated TakeCommentParam p
5859
public BaseResponse<String> genTranslate(@RequestBody @Validated TranslateParam param) {
5960
String traceId = genTraceId();
6061
threadPoolExecutor.submit(() -> {
61-
MDC.put(TRACE_ID,traceId);
62+
MDC.put(TRACE_ID, traceId);
6263
aigcManager.translateToChinese(param);
6364
});
6465
return ResultUtil.success("");
@@ -70,12 +71,30 @@ public BaseResponse<String> judgeOnlineJava(@RequestBody @Validated OJParam para
7071
ThrowUtil.throwIf(!param.getLanguage().equals("Java"), ErrorCode.PARAMS_ERROR, "unavailable language :%s ".formatted(param.getCode()));
7172
String traceId = genTraceId();
7273
threadPoolExecutor.submit(() -> {
73-
MDC.put(TRACE_ID,traceId);
74+
MDC.put(TRACE_ID, traceId);
7475
judgeService.executeJavaCode(param);
7576
});
7677
return ResultUtil.success("");
7778
}
7879

80+
@PostMapping("/pinyin")
81+
@Operation(summary = "中文拼音转换API)")
82+
public BaseResponse<String> pyConvert(@RequestBody @Validated PinyinConvertParam convertParam) {
83+
return ResultUtil.success(PinyinHelper.toPinyin(convertParam.getText(), convertParam.getType()));
84+
}
85+
86+
@PostMapping("/ocr")
87+
@Operation(summary = "图像文字识别API")
88+
public BaseResponse<String> imageOCR(@RequestBody OCRParam ocrParam) {
89+
try {
90+
File file = FileUtil.base64ToFile(ocrParam.getBase64File(),ocrParam.getSuffix());
91+
return ResultUtil.success(OCRUtil.doOCR(file, ocrParam.getLanguage()));
92+
} catch (Exception e) {
93+
throw new RuntimeException(e);
94+
}
95+
}
96+
97+
7998
private String genTraceId() {
8099
String traceId = MDC.get(TRACE_ID);
81100
if (traceId == null) {

0 commit comments

Comments
 (0)