liuxiaolong
2019-05-06 c15226e1b58f255dbebf1bdca8d4e53b9277249c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package com.basic.analy.controller;
 
import com.alibaba.fastjson.JSONObject;
import com.basic.analy.config.Result;
import com.basic.analy.entity.FaceResults;
import com.basic.analy.service.FaceSdkTool;
import com.basic.analy.service.impl.BbPersonBaseServiceImpl;
import com.basic.analy.service.impl.SearchServiceImpl;
import com.basic.analy.utils.ImageUtils;
import com.cloud.common.model.FileInfos;
import com.cloud.common.utils.FastDFSUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
 
@RestController
@RequestMapping("/esSearch")
public class SearchController {
 
    @Autowired
    private SearchServiceImpl searchService;
    @Value("${es_index_persons}")
    private String  PERSON_PIC_INDEX = "";
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BbPersonBaseServiceImpl baseServiceImpl;
    @Autowired
    private ImageUtils imageUtils;
    @Autowired
    private FastDFSUtil fastDFSUtil;
 
    private Logger log = Logger.getLogger(SearchController.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    /**
     * 供检索模块儿切图使用
     *
     * @param jsonMap
     * @return
     * @throws Exception
     */
    @RequestMapping("/extractFace")
    @ResponseBody
    public Result extractFace(@RequestBody Map jsonMap)
            throws Exception{
        log.info("调用extractFace");
        Object obj = jsonMap.get("fileInfo");
        String s = JSONObject.toJSONString(obj);
        log.info("fileInfo:"+s);
        FileInfos fileInfo = JSONObject.parseObject(s,FileInfos.class);
        Object obj1 = jsonMap.get("picQuality");
        String s1 = JSONObject.toJSONString(obj1);
        Integer picQuality = JSONObject.parseObject(s1,Integer.class);
        Map manyFaceMap = new HashMap();
        try {
            log.info("路径是"+fileInfo.getPath());
            byte[] imgdata = fastDFSUtil.downloadFDFS(fileInfo.getPath());
            log.info("imageData为"+imgdata);
            ArrayList<FaceResults> faceResults = FaceSdkTool.extractFace(imgdata);
            if(faceResults.size()==0){
                log.info("此图中无人脸");
                Map noFaceMap = new HashMap();
                noFaceMap.put("fileName",fileInfo.getName());
                noFaceMap.put("path",fileInfo.getPath());
                noFaceMap.put("reason","未在您上传的图片中检测到人脸,请您核查");
                noFaceMap.put("list",null);
                return Result.custom("比对结束", HttpStatus.OK.value(),true,noFaceMap);
            }else {
                log.info("切出"+faceResults.size()+"张人脸");
                manyFaceMap.put("fileName", fileInfo.getName());
                manyFaceMap.put("path", fileInfo.getPath());
                manyFaceMap.put("reason", null);
                List<FaceResults> list = new ArrayList<>();
                for(FaceResults face: faceResults){
                    log.info("图片质量为"+face.getSocre());
                    if(face.getSocre()*100 > picQuality){
                        list.add(face);
                    }
                }
                manyFaceMap.put("list", list);
            }
 
        } catch (Exception e) {
            log.info("切图异常");
            e.printStackTrace();
        }
        return Result.custom("切图结束", HttpStatus.OK.value(),true,manyFaceMap);
    }
 
    /**
     * 供检索模块儿比对使用
     *
     * @param jsonMap
     * @return
     * @throws Exception
     */
    @RequestMapping("/findLikerPics")
    @ResponseBody
    public Result findLikerPics(@RequestBody Map jsonMap)
            throws Exception{
 
        // 比对条件
        Map param = (Map)jsonMap.get("params");
 
        String filePath = (String) param.get("path");
        List<Map<String, Object>> currentList = new  ArrayList<Map<String, Object>>(); // 比对结果全部集合
        Map resultMap = new HashMap();
        try {
 
            long startTime = System.currentTimeMillis();
            log.info("fastdfs文件路径为"+filePath);
            byte[] imgData = fastDFSUtil.downloadFDFS(filePath);
            ArrayList<FaceResults> faceResults = FaceSdkTool.extractFace(imgData);
 
            byte[] imageData = faceResults.get(0).getFeature();
            int liker = Integer.valueOf(param.get("liker")+"");
 
//            EsThreadUtils.setCurrentList(currentList);
            String FetchSource = "FaceFeature,content,personIsHub,personPicUrl,picAddress,picMaxUrl,picSmUrl";
            log.info("起止时间为"+param.get("startDate")+"===="+param.get("endDate"));
            String startDate = param.get("startDate")!=null?sdf.format(sdf.parse((String) param.get("startDate"))):null;
            String endDate = param.get("endDate")!=null?sdf.format(sdf.parse((String) param.get("endDate"))):null;
 
            currentList = searchService.searchScrollData(PERSON_PIC_INDEX,FetchSource,startDate,endDate,"picDate", liker, imageData);
 
            long endTime = System.currentTimeMillis();
//            currentList = EsThreadUtils.getCurrentList();
            log.info("总时间"+(endTime-startTime)+"currentList:"+currentList.size());
 
            // 排序
            long endTime1 = System.currentTimeMillis();
            Collections.sort(currentList, new Comparator<Map<String,Object>>() {
                public int compare(Map<String,Object> map1, Map<String,Object> map2) {
                    int i = (int) ((Integer)map2.get("likePer") - (Integer)map1.get("likePer"));
                    if(i == 0){
 
                        try {
                            if((sdf1.parse(map2.get("picDate").toString())).getTime() > (sdf1.parse(map1.get("picDate").toString())).getTime()){
                                return 1;
                            }else if((sdf1.parse(map2.get("picDate").toString())).getTime() < (sdf1.parse(map1.get("picDate").toString())).getTime()){
                                return -1;
                            }else{
                                return 0;
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                            return 1;   //抛出异常的话默认大于
                        }
                    }else if(i>0){
                        return 1;
                    }else {
                        return -1;
                    }
                }
            });
            log.info("排序时间     "+(System.currentTimeMillis()-endTime1));
            ListOperations opsForList = redisTemplate.opsForList();
            //把es比对数据放进redis
            if(currentList != null && currentList.size() > 0){
                String esKey = filePath+"_esList";
                redisTemplate.delete(esKey);
                opsForList.rightPushAll(esKey,currentList);
                redisTemplate.expire(esKey,60*10,TimeUnit.SECONDS);
            }
 
 
            //比对人员底库中的人脸数据
            List<Map> baseList = baseServiceImpl.selectLikerPerson(liker, imageData);
            if(baseList != null && baseList.size() > 0) {
                String baseKey = filePath + "_baseList";
                redisTemplate.delete(baseKey);
                log.info("baseList.size:"+baseList.size());
                opsForList.rightPushAll(baseKey, baseList);
                redisTemplate.expire(baseKey, 60 * 10, TimeUnit.SECONDS);
            }
 
        }catch (Exception e) {
            e.printStackTrace();
            log.info("比对异常--"+e.getMessage());
            return Result.custom("比对异常", HttpStatus.OK.value(),false,null);
        }
 
        return Result.custom("比对结束", HttpStatus.OK.value(),true,resultMap);
    }
 
    /**
     * 供布控模块儿切图使用
     *
     * @param jsonMap
     * @return
     * @throws Exception
     */
    @RequestMapping("/extractFaceForControl")
    @ResponseBody
    public Result extractFaceForRetrieve(@RequestBody Map jsonMap)
            throws Exception{
        Object obj = jsonMap.get("fileList");
        String s = JSONObject.toJSONString(obj);
        List list = JSONObject.parseObject(s,List.class);
        List<FileInfos> imgUrlList = new ArrayList<>();
        list.forEach(fileInfo->{
            FileInfos file = JSONObject.parseObject(((JSONObject)fileInfo).toJSONString(),FileInfos.class);
            if(file != null){
                byte[] imgdata = new byte[0];
                try {
                    imgdata = fastDFSUtil.downloadFDFS(file.getPath());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                log.info("路径是"+file.getPath());
                log.info("imageData为"+imgdata);
                ArrayList<FaceResults> faceResults = FaceSdkTool.extractFace(imgdata);
                if(faceResults.size() > 0){
                    log.info("切出"+faceResults.size()+"张人脸");
                    faceResults.forEach(faceResult ->{
                        FileInfos fileUpload = imageUtils.cutPhotoFromFast(file,faceResult.left,faceResult.top,faceResult.width,faceResult.height);
                        imgUrlList.add(fileUpload);
                    });
                }
            }
        });
        return Result.custom("切图结束", HttpStatus.OK.value(),true,imgUrlList);
    }
 
}