앱 서랍 컨텍스트 기반 추천 가중치 버그 수정 및 날짜/시간 로그 보완

- WorkersDb.getContextualRecommendations():
  - 오늘 날짜 로그가 매월/매년 보너스(+15점)를 중복으로 받아 시간대/요일 패턴을 압살하던 버그 수정 (25일/330일 이상 경과한 과거 기록에만 월간/연간 반복 가중치 적용)
  - 자정(23시<->0시) 경계 시간대 비교를 원형 거리로 수정하고 평일/주말 그룹 가중치 및 완만한 7일 반감기 감쇠 적용
  - itemType:itemKey 복합 키로 앱/연락처 키 충돌 방지
- WorkersDb.syncSystemUsageStats(): 외부 실행 로그(AppUsageLog) 생성 시 누락되어 있던 month/dayOfMonth/dayOfWeek/hour 필드 정상 기록
- AppDrawerBottomSheet: 차단/미설치 앱 제외 후에도 최대 18개 추천을 채우도록 여유 후보(limit=40) 조회
This commit is contained in:
2026-11-16 14:34:59 +09:00
parent c6622c8e16
commit 6925c80015
2 changed files with 50 additions and 28 deletions
@@ -404,9 +404,10 @@ class AppDrawerBottomSheet : BottomSheetDialogFragment() {
?.takeIf { it.first == isHiddenSelected } ?.takeIf { it.first == isHiddenSelected }
?.second ?.second
?: run { ?: run {
val scoredItems = WorkersDb.getContextualRecommendations(limit = 18) val scoredItems = WorkersDb.getContextualRecommendations(limit = 40)
val list = mutableListOf<RecommendationItem>() val list = mutableListOf<RecommendationItem>()
for (item in scoredItems) { for (item in scoredItems) {
if (list.size >= 18) break
if (item.type == "APP") { if (item.type == "APP") {
val app = realm.query<AppInfo>("pkgName == $0", item.key).first().find() val app = realm.query<AppInfo>("pkgName == $0", item.key).first().find()
if (app != null && (app.blockRecommend == false || (isHiddenSelected == app.blockRecommend))) { if (app != null && (app.blockRecommend == false || (isHiddenSelected == app.blockRecommend))) {
@@ -229,47 +229,65 @@ object WorkersDb {
// [핵심] 현재 시간 상황에 맞는 추천 리스트 가져오기 // [핵심] 현재 시간 상황에 맞는 추천 리스트 가져오기
fun getContextualRecommendations(limit: Int = 18): List<ScoredItem> { fun getContextualRecommendations(limit: Int = 18): List<ScoredItem> {
val realm = getRealm() val realm = getRealm()
val calendar = Calendar.getInstance() val now = System.currentTimeMillis()
val calendar = Calendar.getInstance().apply { timeInMillis = now }
val curMonth = calendar.get(Calendar.MONTH) val curMonth = calendar.get(Calendar.MONTH)
val curDay = calendar.get(Calendar.DAY_OF_MONTH) val curDay = calendar.get(Calendar.DAY_OF_MONTH)
val curDow = calendar.get(Calendar.DAY_OF_WEEK) val curDow = calendar.get(Calendar.DAY_OF_WEEK)
val curHour = calendar.get(Calendar.HOUR_OF_DAY) val curHour = calendar.get(Calendar.HOUR_OF_DAY)
val ONE_DAY_TIME = 24 * 60 * 60 * 1000 val isCurWeekend = curDow == Calendar.SATURDAY || curDow == Calendar.SUNDAY
// 최근 3개월 데이터만 조회 (너무 오래된 데이터는 노이즈가 됨) val oneDayMs = 24L * 60 * 60 * 1000L
val threeMonthsAgo = System.currentTimeMillis() - (365L * ONE_DAY_TIME)
// 쿼리: 최근 데이터만 가져와서 메모리에서 계산 (복잡한 가중치는 메모리 연산이 빠름) // 최근 1년치 로그 조회 (연간/월간 반복 패턴 포함)
val logs = realm.query<AppUsageLog>("timestamp > $0", threeMonthsAgo).find() val cutoffTime = now - (365L * oneDayMs)
val logs = realm.query<AppUsageLog>("timestamp > $0", cutoffTime).find()
val scores = HashMap<String, Double>() val scores = HashMap<String, Double>()
val keys = HashMap<String, String>()
val types = HashMap<String, String>() val types = HashMap<String, String>()
// 점수 계산
for (log in logs) { for (log in logs) {
var score = 1.0 // 기본 점수 (최근에 썼다는 것 자체로 의미 있음) val daysAgo = ((now - log.timestamp).coerceAtLeast(0L)).toDouble() / oneDayMs
var score = 1.0 // 기본 빈도 점수
// 1. 시간대 매칭 (가장 중요: 아침에 쓰던 앱은 아침에 쓴다) // 1. 시간대 매칭 (자정 23시<->0시 경계 포함 원형 거리)
if (log.hour == curHour) score += 3.0 val rawDiff = kotlin.math.abs(log.hour - curHour)
else if (log.hour == curHour - 1 || log.hour == curHour + 1) score += 1.0 val hourDiff = minOf(rawDiff, 24 - rawDiff)
score += when (hourDiff) {
0 -> 5.0
1 -> 2.5
2 -> 1.0
else -> 0.0
}
// 2. 요일 매칭 (주말/평일 패턴) // 2. 요일 및 평일/주말 패턴 (오늘 당일 로그 중복 보너스 방지)
if (log.dayOfWeek == curDow) score += 2.0 if (daysAgo >= 1.0) {
if (log.dayOfWeek == curDow) {
score += 3.0
} else {
val isLogWeekend = log.dayOfWeek == Calendar.SATURDAY || log.dayOfWeek == Calendar.SUNDAY
if (isLogWeekend == isCurWeekend) score += 1.0
}
}
// 3. "매월 1일" 같은 날짜 패턴 (가중치 매우 높음) // 3. 매월 N일 반복 패턴 (최소 25일 이상 지난 과거 기록에만 적용)
if (log.dayOfMonth == curDay) score += 5.0 if (daysAgo >= 25.0 && log.dayOfMonth == curDay) {
score += 6.0
}
// 4. (옵션) 매년 같은 달 같은 날? (생일 등) // 4. 매년 같은 월/일 반복 패턴 (최소 330일 이상 지난 기록에만 적용)
if (log.month == curMonth && log.dayOfMonth == curDay) score += 10.0 if (daysAgo >= 330.0 && log.month == curMonth && log.dayOfMonth == curDay) {
score += 10.0
}
// 5. 최신성 가중치 (최근 기록일수록 점수 높게) // 5. 완만한 최신성 감쇠 (7일 경과 시 0.5배, 오늘 기록의 독점 방지)
val daysAgo = (System.currentTimeMillis() - log.timestamp).toDouble() / ONE_DAY_TIME val decay = 1.0 / (daysAgo / 7.0 + 1.0)
val decay = 1.0 / (daysAgo + 1) // 오늘이면 1, 9일전이면 0.1
// 최종 점수 누적 val mapKey = "${log.itemType}:${log.itemKey}"
val finalScore = score * decay scores[mapKey] = (scores[mapKey] ?: 0.0) + (score * decay)
scores[log.itemKey] = (scores[log.itemKey] ?: 0.0) + finalScore keys[mapKey] = log.itemKey
types[log.itemKey] = log.itemType types[mapKey] = log.itemType
} }
// 점수 높은 순으로 정렬하여 상위 N개 반환 // 점수 높은 순으로 정렬하여 상위 N개 반환
@@ -277,8 +295,7 @@ object WorkersDb {
.sortedByDescending { it.value } .sortedByDescending { it.value }
.take(limit) .take(limit)
.map { .map {
// 키, 타입, 점수를 묶어서 반환 ScoredItem(keys[it.key] ?: it.key, types[it.key] ?: "APP", it.value)
ScoredItem(it.key, types[it.key] ?: "APP", it.value)
} }
} }
@@ -441,11 +458,15 @@ object WorkersDb {
).find() ).find()
if (existingLog.isEmpty()) { if (existingLog.isEmpty()) {
val logCal = Calendar.getInstance().apply { timeInMillis = lastUsedTime }
copyToRealm(AppUsageLog().apply { copyToRealm(AppUsageLog().apply {
itemKey = pkgName itemKey = pkgName
itemType = "APP" itemType = "APP"
timestamp = lastUsedTime timestamp = lastUsedTime
// month, day 등 날짜 정보 계산해서 넣기... month = logCal.get(Calendar.MONTH)
dayOfMonth = logCal.get(Calendar.DAY_OF_MONTH)
dayOfWeek = logCal.get(Calendar.DAY_OF_WEEK)
hour = logCal.get(Calendar.HOUR_OF_DAY)
}) })
} }
} }