Parcourir la source

加入调用换脸算法

wuweihao il y a 4 ans
Parent
commit
c4acde931e

+ 1 - 1
gis_application/pom.xml

@@ -13,7 +13,7 @@
     <groupId>com.gis</groupId>
     <artifactId>gis_application</artifactId>
     <version>1.0.0</version>
-    <packaging>war</packaging>
+    <packaging>jar</packaging>
     <name>gis_application</name>
     <description>项目入口</description>
 

+ 0 - 13
gis_application/src/main/java/com/gis/ServletInitializer.java

@@ -1,13 +0,0 @@
-package com.gis;
-
-import org.springframework.boot.builder.SpringApplicationBuilder;
-import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
-
-public class ServletInitializer extends SpringBootServletInitializer {
-
-    @Override
-    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
-        return application.sources(GisApplication.class);
-    }
-
-}

+ 17 - 2
gis_application/src/main/resources/application-sit.properties

@@ -6,6 +6,7 @@ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 #spring.datasource.druid.username=root
 #spring.datasource.druid.password=4dkk2020test%
 
+#spring.datasource.druid.url=jdbc:mysql://8.135.106.227:3306/${project.name}?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
 spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/${project.name}?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
 spring.datasource.druid.username=root
 spring.datasource.druid.password=4dkk2021testproject%
@@ -52,14 +53,14 @@ spring.redis.jedis.pool.max-wait=-1ms
 
 
 #log
-logging.path=/root/user/${project.name}_log
+logging.path=/root/data/${project.name}_log
 logging.config=classpath:logback-spring.xml
 logging.level.com.gis=debug
 
 
 
 # file info
-server.file.path=/root/user/${project.name}_data/
+server.file.path=/root/data/${project.name}_data/
 
 # url prefix
 server.url.prefix=/data/
@@ -71,6 +72,20 @@ swagger.description=${swagger.title}
 swagger.version=1.0
 
 
+#oss
+oss.point=http://oss-cn-shenzhen.aliyuncs.com
+oss.key=LTAIUrvuHqj8pvry
+oss.secrecy=JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4
+oss.bucket=oss-xiaoan
+oss.type=oss
+oss.file.path=${project.name}/
+oss.domain=http://ossxiaoan.4dage.com/
+
+# \u5FAE\u4FE1\u4FE1\u606F
+wx.appId=wxbd0f9ff2a5621bf3
+wx.appSecret=94f6cf81ce63fbbf19a155070bb29b60
+
+
 # swagger login
 # \uFFFD\uFFFD\uFFFD\uFFFDbasic\uFFFD\uFFFD\u00BC\uFFFD\uFFFD\u05A4
 #knife4j.basic.enable=true

+ 2 - 2
gis_application/src/main/resources/application.properties

@@ -1,9 +1,9 @@
-server.port=8004
+server.port=8007
 
 spring.profiles.active=dev
 
 # \u9879\u76EE\u540D\u79F0
-project.name=scene_wisdom
+project.name=wx_reload_beijing
 
 # \u8BBF\u95EE\u9759\u6001\u8D44\u6E90\u8BBE\u7F6E
 spring.resources.static-locations=classpath:templates/,classpath:static/,classpath:web/

+ 11 - 0
gis_application/src/main/resources/templates/shutdown.sh

@@ -0,0 +1,11 @@
+#!/bin/bash
+RESOURCE_NAME=wx_reload_beijing.jar
+   tpid=`ps -ef|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
+
+if [ ${tpid} ]; then
+echo 'Kill Process!'
+kill -9 $tpid
+else
+echo 'Stop Success!'
+fi
+

+ 29 - 0
gis_application/src/main/resources/templates/start.sh

@@ -0,0 +1,29 @@
+#!/bin/sh
+RESOURCE_NAME=wx_reload_beijing.jar
+tpid=`ps -ef|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
+if [ ${tpid} ]; then
+echo 'Stop Process...'
+kill -15 $tpid
+fi
+
+sleep 5
+
+tpid=`ps -ef|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
+
+if [ ${tpid} ]; then
+echo 'Kill Process!'
+kill -9 $tpid
+else
+echo 'Stop Success!'
+fi
+
+tpid=`ps -ef|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
+if [ ${tpid} ]; then
+    echo 'App is running.'
+else
+    echo 'App is NOT running.'
+fi
+rm -f tpid
+nohup java -jar ./$RESOURCE_NAME --spring.profiles.active=sit &
+echo $! > tpid
+echo Start Success!

+ 12 - 12
gis_common/pom.xml

@@ -104,18 +104,18 @@
         </dependency>
 
         <!--aliyun sdk-->
-        <!--<dependency>-->
-            <!--<groupId>com.aliyun</groupId>-->
-            <!--<artifactId>aliyun-java-sdk-core</artifactId>-->
-        <!--</dependency>-->
-        <!--<dependency>-->
-            <!--<groupId>com.aliyun</groupId>-->
-            <!--<artifactId>aliyun-java-sdk-dysmsapi</artifactId>-->
-        <!--</dependency>-->
-        <!--<dependency>-->
-            <!--<groupId>com.aliyun.oss</groupId>-->
-            <!--<artifactId>aliyun-sdk-oss</artifactId>-->
-        <!--</dependency>-->
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>aliyun-java-sdk-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+        </dependency>
 
 
         <!--tk.mybatis 依赖-->

+ 18 - 0
gis_common/src/main/java/com/gis/common/constant/CmdConstant.java

@@ -0,0 +1,18 @@
+package com.gis.common.constant;
+
+
+/**
+ * Created by owen on 2020/12/31 0031 14:22
+ *
+ */
+public class CmdConstant {
+
+
+    /**
+     * 算法换装命令
+     *
+     * */
+    public final static String FACE_SWAP = "face_swap -i @input -t @type -o @output";
+
+
+}

+ 3 - 0
gis_common/src/main/java/com/gis/common/constant/MsgCode.java

@@ -27,4 +27,7 @@ public class MsgCode {
 
     public final static Integer e5004 = 5004;
     public final static String m5004 = "密码错误";
+
+    /** 调用算法换脸失败*/
+    public final static Integer e5005 = 5005;
 }

+ 209 - 0
gis_common/src/main/java/com/gis/common/util/AliyunOssUtil.java

@@ -0,0 +1,209 @@
+package com.gis.common.util;
+
+import com.aliyun.oss.OSSClient;
+import com.aliyun.oss.model.OSSObject;
+import com.aliyun.oss.model.OSSObjectSummary;
+import com.aliyun.oss.model.ObjectListing;
+import com.gis.common.constant.ConfigConstant;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 阿里云oss工具类
+ */
+@Slf4j
+@Component
+public class AliyunOssUtil {
+
+    @Autowired
+    ConfigConstant configConstant;
+
+    private OSSClient init(){
+        return new OSSClient(configConstant.ossPoint, configConstant.ossKey, configConstant.ossSecrecy);
+    }
+
+
+    public void delete(String key) throws IOException {
+        OSSClient ossClient = init();
+        try {
+
+            // 2019-2-28 启动aliyun oss 空间
+            ossClient.deleteObject(configConstant.ossBucket, key);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    //上传的数据是byte[],key是上传后的文件名
+    public void upload(byte[] data, String key) throws IOException {
+        OSSClient ossClient = init();
+        try {
+            // 2019-2-28 启动aliyun oss 空间
+            ossClient.putObject(configConstant.ossBucket, key, new ByteArrayInputStream(data));
+        } catch (Exception e) {
+            log.error(e.toString() + key);
+        }
+    }
+
+
+    public void upload(String filePath, String key) {
+        OSSClient ossClient = init();
+        try {
+            File file = new File(filePath);
+            if (!file.exists()) {
+                log.error("要上传的文件不存在:" + filePath);
+            }
+            ossClient.putObject(configConstant.ossBucket, key, new File(filePath));
+
+        } catch (Exception e) {
+            log.error(e.toString() + filePath);
+        }
+    }
+
+    public  void upload2(String filePath, String key) {
+        OSSClient ossClient = init();
+        try {
+
+            // 2019-2-28 启动aliyun oss 空间
+            ossClient.putObject(configConstant.ossBucket, key, new File(filePath));
+        } catch (Exception e) {
+            log.error(e.toString() + filePath);
+        }
+    }
+
+
+    /**
+     * 上传的数据是文件夹,参数是文件夹路径,key是上传后的文件名
+     *
+     * @param filepaths key : 原文件路径
+     *                  value: oss路径, oss会自动创建目录
+     */
+
+    public  void uploadMulFiles(Map<String, String> filepaths) {
+        if (filepaths == null) {
+            return;
+        }
+        log.info("开始批量上传到阿里云:" + new Date().toString());
+        if (filepaths.size() > 50) {
+            int i = 1;
+            for (String filePath : filepaths.keySet()) {
+                if (i%100 == 0) {
+
+                    log.info("i= " +i + ", 文件:" + filePath + "到阿里云:" + filepaths.get(filePath));
+                }
+                upload2(filePath, filepaths.get(filePath));
+                i ++ ;
+            }
+            log.info("上传文件数量:"+ i);
+        } else {
+            for (String filePath : filepaths.keySet()) {
+                log.debug("文件:" + filePath + "到阿里云:" + filepaths.get(filePath));
+                upload(filePath, filepaths.get(filePath));
+            }
+        }
+        log.info("批量上传阿里云完毕:" + new Date().toString());
+    }
+
+
+    /**
+     * 可以删除目录
+     *
+     * @param prefix 图片路径
+     * @return
+     */
+    public  int deleteFile(String prefix) {
+        OSSClient ossClient = init();
+        ObjectListing objectListing = ossClient.listObjects(configConstant.ossBucket, prefix);
+        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
+        try {
+            for (OSSObjectSummary s : sums) {
+                delete(s.getKey());
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return sums.size();
+    }
+
+
+
+
+
+
+
+
+    /**
+     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
+     *
+     * @param fileName 文件名
+     * @return 文件的contentType
+     */
+    private static String getContentType(String fileName) {
+        log.info("getContentType:" + fileName);
+        // 文件的后缀名
+        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
+        if (".bmp".equalsIgnoreCase(fileExtension)) {
+            return "image/bmp";
+        }
+        if (".gif".equalsIgnoreCase(fileExtension)) {
+            return "image/gif";
+        }
+        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
+                || ".png".equalsIgnoreCase(fileExtension)) {
+            return "image/jpeg";
+        }
+        if (".html".equalsIgnoreCase(fileExtension)) {
+            return "text/html";
+        }
+        if (".txt".equalsIgnoreCase(fileExtension)) {
+            return "text/plain";
+        }
+        if (".vsd".equalsIgnoreCase(fileExtension)) {
+            return "application/vnd.visio";
+        }
+        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
+            return "application/vnd.ms-powerpoint";
+        }
+        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
+            return "application/msword";
+        }
+        if (".xml".equalsIgnoreCase(fileExtension)) {
+            return "text/xml";
+        }
+        if (".pdf".equalsIgnoreCase(fileExtension)) {
+            return "application/pdf";
+        }
+        // 默认返回类型
+        return "image/jpeg";
+    }
+
+    /**
+     * 以流下载图片
+     *
+     * @param
+     * @return
+     * @Title: getInputStreamByFileUrl
+     * @Description: 根据文件路径获取InputStream流
+     * @return: InputStream
+     */
+    public InputStream getInputStreamByFileUrl(String filePath) {
+        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
+        OSSClient ossClient = init();
+        OSSObject ossObject = ossClient.getObject(configConstant.ossBucket, filePath);
+        return ossObject.getObjectContent();
+    }
+
+
+
+
+
+}

+ 52 - 0
gis_common/src/main/java/com/gis/common/util/CmdUtils.java

@@ -0,0 +1,52 @@
+package com.gis.common.util;
+
+import lombok.extern.slf4j.Slf4j;
+import org.junit.Test;
+
+/**
+ * Created by owen on 2021/1/4 0004 14:53
+ */
+@Slf4j
+public class CmdUtils {
+
+
+    /**
+     * 调用算法 SHELL 脚本
+     * @param command
+     *
+     *
+     * String[] cmd = new String[]{"/bin/sh", "-c", command}; 调用异常,可以使用这个试试
+     */
+    public static void callLine(String command) throws Exception{
+        callLine(command, null);
+
+    }
+
+    /**
+     *
+     * @param command 命令
+     * @param lineSize 日志输出行数 ,可以为null
+     */
+    public static void callLine(String command, Integer lineSize) throws Exception{
+        log.info("cmd: " + command);
+
+            Process process = Runtime.getRuntime().exec(command);
+            log.info("开始运行");
+            StreamGobblerLine errorGobbler = new StreamGobblerLine(process.getErrorStream(), "ERROR");
+            errorGobbler.start();
+            // 200行打印一次日志
+            StreamGobblerLine outGobbler = new StreamGobblerLine(process.getInputStream(), "STDOUT", lineSize);
+            outGobbler.start();
+            process.waitFor();
+    }
+
+
+
+    @Test
+    public void test() throws Exception{
+        CmdUtils.callLine("ipconfig");
+    }
+
+
+
+}

+ 80 - 0
gis_common/src/main/java/com/gis/common/util/StreamGobblerLine.java

@@ -0,0 +1,80 @@
+package com.gis.common.util;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.io.*;
+
+@Slf4j
+public class StreamGobblerLine extends Thread {
+
+	InputStream is;
+    String type;
+    OutputStream os;
+    Integer lineSize;  // 多少行打印日志一次
+
+    public StreamGobblerLine(InputStream is, String type) {
+        this(is, type, null, null);
+    }
+
+    public StreamGobblerLine(InputStream is, String type, Integer lineSize) {
+        this(is, type, null, lineSize);
+    }
+
+    StreamGobblerLine(InputStream is, String type, OutputStream redirect, Integer lineSize) {
+        this.is = is;  
+        this.type = type;  
+        this.os = redirect;
+        this.lineSize = lineSize;
+    }  
+
+    public void run() {
+        log.info("run StreamGobblerLine");
+
+        InputStreamReader isr = null;  
+        BufferedReader br = null;  
+        PrintWriter pw = null;  
+        try {  
+            if (os != null)  
+                pw = new PrintWriter(os);  
+
+            isr = new InputStreamReader(is);  
+            br = new BufferedReader(isr);  
+            String line=null;
+            int i = 1;
+            while ( (line = br.readLine()) != null) {
+//                pw.println(line);
+                if (lineSize != null) {
+                    if (i % lineSize == 0) {
+                        log.info(type + "," + i +" : >" + line);
+                    }
+                } else {
+                    log.info(type + ","  + i +" : >" + line);
+                }
+                i++;
+
+            }
+
+            if (pw != null)  
+                pw.flush();  
+        } catch (IOException ioe) {  
+            ioe.printStackTrace();    
+        } finally{  
+            try {  
+            	if(pw!=null)
+            	{
+            		 pw.close();  
+            	}
+            	if(br!=null)
+            	{
+            		br.close();  
+            	}
+            	if(isr!=null)
+            	{
+            		isr.close();  
+            	}
+            } catch (IOException e) {  
+                e.printStackTrace();  
+            }  
+        }  
+    }  
+}

+ 13 - 0
gis_service/src/main/java/com/gis/service/UploadService.java

@@ -0,0 +1,13 @@
+package com.gis.service;
+
+import com.gis.common.util.Result;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * Created by owen on 2021/4/29 0029 17:32
+ */
+public interface UploadService {
+
+     Result uploadFaceSwap(MultipartFile file, String type);
+
+}

+ 85 - 0
gis_service/src/main/java/com/gis/service/impl/UploadServiceImpl.java

@@ -0,0 +1,85 @@
+package com.gis.service.impl;
+
+import cn.hutool.core.date.DateUtil;
+import cn.hutool.core.io.FileUtil;
+import com.gis.common.constant.CmdConstant;
+import com.gis.common.constant.ConfigConstant;
+import com.gis.common.constant.MsgCode;
+import com.gis.common.exception.BaseRuntimeException;
+import com.gis.common.util.AliyunOssUtil;
+import com.gis.common.util.CmdUtils;
+import com.gis.common.util.Result;
+import com.gis.service.UploadService;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.util.Date;
+
+
+/**
+ * Created by owen on 2020/3/11 0011 16:16
+ */
+@Slf4j
+@Service
+public class UploadServiceImpl implements UploadService {
+
+    @Autowired
+    ConfigConstant configConstant;
+
+    @Autowired
+    AliyunOssUtil aliyunOssUtil;
+
+    @Override
+    public Result uploadFaceSwap(MultipartFile file, String type) {
+        String originalFilename = file.getOriginalFilename();
+        String suffix = StringUtils.substringAfterLast(originalFilename, ".");
+        String time = DateUtil.format(new Date(), "yyyyMMdd_HHmmssSSS");
+        String basePath = configConstant.serverBasePath + time;
+        String filePath = basePath + "/face." + suffix;
+        log.info("filePath: " + filePath);
+        String faceSwapName = time + "/faceSwap." + suffix;
+        log.info("faceSwapName: " + faceSwapName);
+        String ossUrl = null;
+        try {
+            FileUtil.writeFromStream(file.getInputStream(), filePath);
+            log.info("文件写入完成");
+
+            // 换装并上传
+             ossUrl = cmdReloadAndUploadOss(filePath, faceSwapName, type);
+            return Result.success(ossUrl);
+            //发消息到mq
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new BaseRuntimeException(MsgCode.e5005, "换脸失败");
+        }
+
+    }
+
+    private String cmdReloadAndUploadOss(String input, String faceSwapName, String type) throws Exception {
+        String output = configConstant.serverBasePath + faceSwapName;
+        log.info("output: " + output);
+        String cmd = CmdConstant.FACE_SWAP;
+        cmd = cmd.replace("@input", input);
+        cmd = cmd.replace("@output", output);
+        cmd = cmd.replace("@type", type);
+        log.info("cmd: {}", cmd);
+        CmdUtils.callLine(cmd);
+        log.info("换装完成: {}", output);
+
+        String ossKey = configConstant.ossBasePath + faceSwapName;
+        aliyunOssUtil.upload(output, ossKey);
+        String ossUrl = configConstant.ossDomain + ossKey;
+        log.info("oss上传完成: {}", ossUrl);
+        return ossUrl;
+
+    }
+
+
+
+
+
+
+}

+ 38 - 0
gis_web/src/main/java/com/gis/web/controller/UploadController.java

@@ -0,0 +1,38 @@
+package com.gis.web.controller;
+
+import com.gis.common.util.Result;
+import com.gis.service.UploadService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * Created by owen on 2021/4/30 0013 14:45
+ */
+@Slf4j
+@Api(tags = "文件上传")
+@RestController
+@RequestMapping("api")
+public class UploadController {
+
+    @Autowired
+    UploadService uploadService;
+
+
+    @ApiOperation(value = "上传换装图片", notes = "type:类型")
+    @PostMapping("uploadFaceSwap/{type}")
+    public Result uploadReload(MultipartFile file, @PathVariable String type){
+        return uploadService.uploadFaceSwap(file, type);
+    }
+
+
+
+
+
+}

+ 18 - 18
pom.xml

@@ -194,24 +194,24 @@
             </dependency>
 
             <!--aliyun sdk-->
-            <!--<dependency>-->
-                <!--<groupId>com.aliyun</groupId>-->
-                <!--<artifactId>aliyun-java-sdk-core</artifactId>-->
-                <!--<version>${aliyun.core.version}</version>-->
-            <!--</dependency>-->
-
-            <!--<dependency>-->
-                <!--<groupId>com.aliyun</groupId>-->
-                <!--<artifactId>aliyun-java-sdk-dysmsapi</artifactId>-->
-                <!--<version>${aliyun.dysmsapi.version}</version>-->
-            <!--</dependency>-->
-
-            <!--&lt;!&ndash;aliyun oss&ndash;&gt;-->
-            <!--<dependency>-->
-                <!--<groupId>com.aliyun.oss</groupId>-->
-                <!--<artifactId>aliyun-sdk-oss</artifactId>-->
-                <!--<version>${aliyun.oss.version}</version>-->
-            <!--</dependency>-->
+            <dependency>
+                <groupId>com.aliyun</groupId>
+                <artifactId>aliyun-java-sdk-core</artifactId>
+                <version>${aliyun.core.version}</version>
+            </dependency>
+
+            <dependency>
+                <groupId>com.aliyun</groupId>
+                <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
+                <version>${aliyun.dysmsapi.version}</version>
+            </dependency>
+
+            <!--aliyun oss-->
+            <dependency>
+                <groupId>com.aliyun.oss</groupId>
+                <artifactId>aliyun-sdk-oss</artifactId>
+                <version>${aliyun.oss.version}</version>
+            </dependency>
 
 
             <!--tk.mybatis 依赖-->