Skip to content

Commit

Permalink
Merge pull request #262 from limbaba1120/deploy
Browse files Browse the repository at this point in the history
Deploy v2.0.8
  • Loading branch information
limbaba1120 authored Aug 29, 2024
2 parents d0c94bf + f9101b3 commit 0430485
Show file tree
Hide file tree
Showing 55 changed files with 2,819 additions and 190 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
public class ApiStorageException extends ApiException {

@Builder
protected ApiStorageException(
public ApiStorageException(
ApiErrorCategory category,
ApiStorageErrorSubCategory subCategory,
@Nullable Supplier<?> setErrorData
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class AsyncImageAnalyzePipeline {
* 분석이 종료되기 까지 평균 1.5초 소요됬던 점을 바탕으로 1000ms로 설정 했습니다.
*/
private static final int UPDATE_SCORE_PENDING_WAIT_MS = 1000;
private static final int UPDATE_SCORE_MAX_TIMEOUT_MS = 5000;
protected static final int UPDATE_SCORE_MAX_TIMEOUT_MS = 5000;

private final ImageAnalyzeManager imageAnalyzeManager;
private final ImageRedisService imageRedisService;
Expand Down Expand Up @@ -116,12 +116,12 @@ public void updateScore(Long imageLocationId, UpdateScoreType updateScoreType)

// --------------------------------------------------------------------------
// Internal Methods
private boolean isScoreInitialized(Long imageLocationId) {
protected boolean isScoreInitialized(Long imageLocationId) {
return !this.onGoingTasks.contains(imageLocationId);

}

private final Consumer<Integer> pendingTask = (ms) -> {
protected final Consumer<Integer> pendingTask = (ms) -> {
try {
log.debug("Pending task... - sleep {}ms", ms);
Thread.sleep(ms);
Expand Down Expand Up @@ -168,18 +168,18 @@ private boolean isScoreInitialized(Long imageLocationId) {
}
log.debug("(3) Image analyze pipeline done - image {}", imageLocationId);
};

/**
* @deprecated 아직 구현되지 않은 기능입니다.
/*
*//**
* @ deprecated 아직 구현되지 않은 기능입니다.
* 기존엔 옷 카테고리를 사용자가 직접 입력했습니다.
* 이를 사용자가 하지 않고, 이미지 분석 결과로 부터 자동으로 설정되도록 하고자 한 시도입니다.
* 추후에 구현이 될지 모르지만, 일단 코드를 남깁니다.
*/
*//*
private final BiConsumer<ImageAnalyzeManager, Long> mapAnalyzedClothCategoryWithPostTask = (analyzeManager, imageLocationId) -> {
// 1. get cloth analyzed data
List<ClothAnalyzeData> clothAnalyzeDataList
= analyzeManager.getAnalyzedData(imageLocationId).clothAnalyzeDataList();
// 2. set cloth category
// 분석 결과를 가지고 Post Entity의 카테고리와 매핑합니다.
};
};*/
}
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ private List<GoogleImagenVisionDto.ClothDetection> detectClothObjects(
}

@LogExecution
private static RGBColor extractColorProperties(
protected static RGBColor extractColorProperties(
ByteString imgBytes,
ImageAnnotatorClient client
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,13 @@ public static GoogleApiCredentialRoller fromEnv(String env_name) {
return new GoogleApiCredentialRoller(env_name);
}

protected static String getEnv(String envName) {
return System.getenv(envName);
}

protected GoogleApiCredentialRoller(String env_name) {
// init credentials with given env files
JsonArray keys = JsonParser.parseString(System.getenv(env_name)).getAsJsonArray();
JsonArray keys = JsonParser.parseString(getEnv(env_name)).getAsJsonArray();
keys.forEach(key -> {
try {
this.credentialsList.add(GoogleCredentials.fromStream(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,40 +9,40 @@ public class ColorConverter {
// private static final float[] STANDARD_TRISTIMULUS_D50 = {96.42f, 100.000f, 82.49f};
private static final float[] STANDARD_TRISTIMULUS_D65 = {95.047f, 100.000f, 108.883f}; // general type
private static final float[] STANDARD_TRISTIMULUS_A = {109.85f, 100.000f, 35.585f}; // relatively dark type

/**
/*
*//**
* RGB -> CIE-LAB.
* @param red Red coefficient. Values in the range [0..255].
* @param green Green coefficient. Values in the range [0..255].
* @param blue Blue coefficient. Values in the range [0..255].
* @return CIE-LAB color space.
*/
* @ param red Red coefficient. Values in the range [0..255].
* @ param green Green coefficient. Values in the range [0..255].
* @ param blue Blue coefficient. Values in the range [0..255].
* @ return CIE-LAB color space.
*//*
// float[] tristimulus param maybe need if more accurate converter for specific environment or lighting condition
public static float[] RGBtoLAB(int red, int green, int blue, float[] tri){
float[] xyz = RGBtoXYZ(red, green, blue);
float[] lab = XYZtoLAB(xyz[0], xyz[1], xyz[2], tri);
return lab;
}
}*/

public static LabColor RGBtoLAB(RGBColor rgbColor, float[] tri) {
float[] xyz = RGBtoXYZ(rgbColor.getRed(), rgbColor.getGreen(), rgbColor.getBlue());
float[] lab = XYZtoLAB(xyz[0], xyz[1], xyz[2], tri);
return new LabColor(lab[0], lab[1], lab[2]);
}

/**
/* *//**
* CIE-LAB -> RGB.
* @param l L coefficient.
* @param a A coefficient.
* @param b B coefficient.
* @return RGB color space.
*/
* @ param l L coefficient.
* @ param a A coefficient.
* @ param b B coefficient.
* @ return RGB color space.
*//*
// float[] tristimulus param maybe need if more accurate converter for specific environment or lighting condition
public static int[] LABtoRGB(float l, float a, float b, float[] tri){
float[] xyz = LABtoXYZ(l, a, b, tri);
return XYZtoRGB(xyz[0], xyz[1], xyz[2]);
}
}*/

/**
* XYZ -> CIE-LAB.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

public class ImageCropper {

private final BufferedImage originalImage;
protected final BufferedImage originalImage;

public ImageCropper(byte[] imgBytes) {
this.originalImage = createBufferdImageFromBytes(imgBytes);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class LabColorSimilarity {
* @param lab2 The second LAB color as a float array.
* @return The Euclidean distance.
*/
private static double calculateEuclideanDistance(float[] lab1, float[] lab2) {
protected static double calculateEuclideanDistance(float[] lab1, float[] lab2) {
return Math.sqrt(Math.pow(lab1[0] - lab2[0], 2) +
Math.pow(lab1[1] - lab2[1], 2) +
Math.pow(lab1[2] - lab2[2], 2));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public StorageLoadResult load(@NonNull String filePath) {
}
}

private void createDirectory(@NonNull Path path) {
protected void createDirectory(@NonNull Path path) {
try {
Files.createDirectories(path);
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public record ColorSelectedDtoRequest(
) {

}

public record ColorUpdateDtoRequest(
String name,
Integer r,
Expand All @@ -53,6 +54,15 @@ public record ColorUpdateDtoRequest(
Integer originB
) {

}

public record ColorPopularResponse(
String name,
Integer r,
Integer g,
Integer b
){

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,22 @@
import static org.example.image.ImageAnalyzeManager.analyzer.tools.ColorConverter.*;
import static org.example.image.redis.tools.RgbColorSimilarity.*;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import org.example.config.log.LogExecution;
import org.example.image.ImageAnalyzeManager.ImageAnalyzeManager;
import org.example.image.ImageAnalyzeManager.analyzer.type.ClothAnalyzeData;
import org.example.image.ImageAnalyzeManager.type.ImageAnalyzeData;
import org.example.image.redis.ColorApiClient;
import org.example.image.redis.domain.dto.ColorDto;
import org.example.config.log.LogExecution;
import org.example.post.domain.entity.PostEntity;
import org.example.post.domain.enums.PostStatus;
import org.example.post.repository.PostRepository;
Expand All @@ -27,6 +29,7 @@
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -45,16 +48,16 @@ public class ImageRedisService {
private final PostRepository postRepository;
private final ImageAnalyzeManager imageAnalyzeManager;

private static final String HASH_KEY = "ColorHash";
private static final String ZSET_KEY = "ColorZSet";
protected static final String HASH_KEY = "ColorHash";
protected static final String ZSET_KEY = "ColorZSet";
private static final String COLOR_DIST_CAL_ZSET_KEY = "ColorDistCalZSet";
private static final Integer STANDARD_DIST = 10;
private static final Integer WEIGHT_LDT = 1;
private static final Integer WEIGHT_LIKE = 1;
private static final Integer WEIGHT_VIEW = 1;

@LogExecution
public List<String> saveNewColor(Long imageLocationId) throws JsonProcessingException {
public List<String>saveNewColor(Long imageLocationId) throws JsonProcessingException {
List<String> colorNameList = new ArrayList<>();
ColorApiClient client = new ColorApiClient();
HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
Expand Down Expand Up @@ -226,7 +229,7 @@ public void updateZSetColorScore(
String colorName = calcCloseColorsDist(rgbColor, 1).get(0).name();

Double currentScore = zSetOps.score(ZSET_KEY, colorName);
if(currentScore == null){
if (currentScore == null) {
currentScore = 0.0;
}
currentScore += updateScoreType.getValue();
Expand All @@ -235,9 +238,39 @@ public void updateZSetColorScore(
}
}

public List<ColorDto.ColorPopularResponse> getPopularColorList() {
HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
ObjectMapper objectMapper = new ObjectMapper();

// Return most popular 10 color as list of name and rgb
Set<ZSetOperations.TypedTuple<Object>> typedTuples = zSetOps.reverseRangeWithScores(ZSET_KEY, 0, 9);

assert typedTuples != null;

return typedTuples.stream()
.map(
tuple -> {
String colorName = (String)tuple.getValue();
JsonNode rootNode;
try {
rootNode = objectMapper.readTree(hashOps.get(HASH_KEY, colorName).toString());
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}

int[] rgb = {rootNode.get("r").asInt(), rootNode.get("g").asInt(), rootNode.get("b").asInt()};
return new ColorDto.ColorPopularResponse(
colorName,
rgb[0], rgb[1], rgb[2]
);
}
).toList();
}

// Private Internal Method -------------------------------------------------------------------
@LogExecution
private List<ColorDto.ColorDistanceResponse> calcCloseColorsDist(
protected List<ColorDto.ColorDistanceResponse> calcCloseColorsDist(
int[] rgb, int num
) throws JsonProcessingException {
HashOperations<String, Object, Object> hashOps = redisTemplate.opsForHash();
Expand Down Expand Up @@ -321,7 +354,7 @@ public List<int[]> getCloseColorList(int[] rgb, int num)
}

@LogExecution
private double calcScoreOfPost(PostPopularSearchCondition condition) {
protected double calcScoreOfPost(PostPopularSearchCondition condition) {
double score = 0.0;

Duration duration = Duration.between(condition.getCreatedAt(), LocalDateTime.now());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import java.util.List;

import org.example.config.log.LogExecution;
import org.example.image.redis.domain.dto.ColorDto;
import org.example.image.redis.service.ImageRedisService;
import org.example.post.domain.dto.PostDto;
import org.example.post.domain.entity.CategoryEntity;
import org.example.post.repository.custom.CategoryAndColorSearchCondition;
Expand Down Expand Up @@ -36,6 +38,7 @@
@RequiredArgsConstructor
public class PostPublicController {
private final PostService postService;
private final ImageRedisService imageRedisService;

@GetMapping("")
public ResponseEntity<Page<PostDto.PostDtoResponse>> searchPost(
Expand Down Expand Up @@ -135,5 +138,13 @@ public ResponseEntity<List<CategoryEntity>> getCategoryAll() {
return ResponseEntity.status(HttpStatus.OK).body(categoryList);
}

@GetMapping("/popular_color")
public ResponseEntity<List<ColorDto.ColorPopularResponse>> getPopularColor(){
List<ColorDto.ColorPopularResponse> colorPopularResponses =
imageRedisService.getPopularColorList();

return ResponseEntity.status(HttpStatus.OK).body(colorPopularResponses);
}

}

Loading

0 comments on commit 0430485

Please sign in to comment.