DOCS/troubleshooting/20251002_emotion_system_implementation.md
happybell80 64c2f077e4 Update: 감정 시스템 구현 계획에 TimescaleDB 권장사항 추가
- emotion_readings를 TimescaleDB 하이퍼테이블로 구현 권장
- robeing_metrics DB 사용하여 main_db와 분리
- rb8001 중복 코드 정리 문서 날짜 업데이트
2025-10-02 10:05:49 +09:00

7.4 KiB

감정 시스템 구현 계획 (rb8001)

작성일: 2025-10-02 작성자: Claude & happybell80 관련 서비스: rb8001 이슈: 감정 분석 시스템 미구현

현재 상황

rb8001 감정 시스템 현황

  • 구조만 존재: rb8001/app/core/emotion/base.py:16-34, rb8001/app/llm/emotion_llm.py:18-114
  • 실제 분석 없음: rb8001/app/core/emotion/base.py:46-55 (모든 감정 균등 분포 반환)
  • rb10508_micro: rb10508_micro/app/core/emotion/base.py:46-55 (동일 구조)

서버 확인 결과 (2025-10-02)

51124 서버 확인 사항

# 확인 필요
docker exec rb8001 ls -la /code/app/core/emotion/  # emotion 파일 목록
docker exec rb8001 cat /code/app/core/emotion/emotion_llm.py  # 구현 코드
docker exec rb8001 ls -la /code/onnx_models/  # ONNX 모델 존재 여부
docker logs rb8001 --tail 1000 | grep -i emotion  # 감정 로그
curl http://localhost:8001/v1/emotion/infer -X POST -d '{"text":"테스트"}'  # API 테스트

# 전체 서비스 확인
for container in rb8001 skill-embedding robeing_monitor skill-rag-file; do
  echo "=== $container ==="
  docker exec $container find /code -name "*emotion*" 2>/dev/null
done

51123 서버 확인 결과

  • PostgreSQL: emotion_readings 테이블 없음
  • 모델 파일: /opt/models에 감정 모델 없음 (sentence-transformer만 존재)
  • API 엔드포인트: /v1/emotion/* 엔드포인트 없음 ("Endpoint not found")
  • Gateway 서비스: robeing-gateway 실행 중 (포트 8100)
  • 결론: 51123에 감정 시스템 관련 인프라 전혀 구현되지 않음

구현된 부분

rb8001/app/core/emotion/base.py:16-34  EmotionState 정의 (9개 감정 레이블 포함)
rb8001/app/core/emotion/base.py:37-44  calculate_entropy[_cached]
rb8001/app/core/emotion/base.py:128-155 ThompsonSampler
rb8001/app/llm/emotion_llm.py:25-54  analyze_user_emotion (analyze_emotion 호출)
rb8001/app/llm/emotion_llm.py:56-89  generate_response_with_emotion (메모리 저장)

미구현 부분

  1. 모델 통합: klue/bert-base 기반 7클래스 분류기 (코드 없음)
  2. ONNX 추론: 모델 변환 및 최적화 (코드 없음)
  3. Temperature Scaling: 확률 보정 (코드 없음)
  4. 데이터베이스: emotion_readings 테이블 (스키마/마이그레이션 없음)
  5. API 엔드포인트: /v1/emotion/infer 등 (엔드포인트 없음)

구현 로드맵

Phase 1: 기본 감정 분석 (1주)

  1. Day 1-2: 모델 준비

    • klue/bert-base 기반 감정 분류 모델 준비
    • 7개 클래스: fear, surprise, anger, sadness, neutral, happiness, disgust
    • ONNX 변환 및 최적화
  2. Day 3-4: 추론 엔진 구현

    없음: rb8001/app/core/emotion/inference.py (파일 미존재)
    없음: rb8001 내 onnxruntime/transformers 런타임 사용 코드
    참고: training_emotion/train_korean_emotion.py:244-257 (학습용 ORT/Tokenizer)
    현재 추론 경로: rb8001/app/core/emotion/base.py:63-85 (analyze_emotion[_cached])
    현재 LLM 연동: rb8001/app/llm/emotion_llm.py:25-54 (analyze_user_emotion)
    토크나이저/ONNX 세션 초기화 위치: 없음 (프로덕션 코드 기준)
    EMOTION_TEMPERATURE 사용: rb8001/app/core/emotion/base.py:14 (상수 로드)
    Temperature Scaling 적용: 없음 (확률 보정 미적용)
    모델 파일 경로 상수: 없음
    레이블 상수(7클래스): 없음
    추론 입력 전처리: 없음
    추론 출력 후처리: 없음
    배치 추론 엔트리포인트: 없음
    에러 처리/재시도: 없음
    로깅 위치: rb8001/app/llm/emotion_llm.py:49 (분석 결과 로그)
    
  3. Day 5: DB 스키마 구현 (TimescaleDB 권장)

    없음: emotion_readings 테이블 (코드/마이그레이션 미존재)
    확인: DOCS/ideas/emotion_graph_implementation.md:215,232 (문서 내 예시 스키마)
    확인: DOCS/ideas/250916_로빙_감정_분석_시스템_구현_계획.md:11 (테이블 부재 명시)
    
    [TimescaleDB 적용 권장]
    - emotion_readings는 시계열 데이터로 TimescaleDB 하이퍼테이블이 적합
    - robeing_metrics DB 사용 (main_db와 분리)
    - 참고: frontend-base/backend/metrics_database.py:103 (time_bucket 쿼리)
    - 참고: DOCS/troubleshooting/250714_system_metrics_implementation.md
    
    CREATE TABLE emotion_readings (
      time TIMESTAMPTZ NOT NULL,
      user_id UUID NOT NULL,
      text_hash VARCHAR(64),
      model_version VARCHAR(20),
      temperature FLOAT,
      logits JSONB,
      probs JSONB,
      top_label VARCHAR(20),
      top_p FLOAT,
      entropy FLOAT,
      meta JSONB
    );
    
    SELECT create_hypertable('emotion_readings', 'time');
    CREATE INDEX ON emotion_readings (user_id, time DESC);
    

Phase 2: API 및 통합 (1주)

  1. Day 6-7: API 엔드포인트

    없음: rb8001 내 /v1/emotion/* 라우트
    확인: rg 검색 결과 엔드포인트 미발견
    관련 파일: rb8001/main.py (감정 관련 API 없음)
    현재 사용 경로: rb8001/app/llm/llm_service.py:119-134 (내부 호출만 존재)
    robeing-gateway/app/main.py (프록시에 감정 API 없음)
    robeing-monitor (감정 API 없음)
    
  2. Day 8-9: 기존 시스템 통합

    • Router에서 감정 분석 호출
    • 메모리 저장 시 감정 메타데이터 추가
    • Slack 응답에 감정 정보 포함
  3. Day 10: 시각화

    • 감정 그래프 생성 (matplotlib/plotly)
    • Slack 이미지 업로드

Phase 3: 고도화 (선택적)

  1. Temperature Calibration

    • 검증 데이터셋으로 최적 T 값 찾기
    • ECE (Expected Calibration Error) 최소화
  2. 배치 처리 최적화

    • 마이크로배칭
    • 비동기 처리 큐
  3. 감정 공명 시스템

    • 과거 감정과 현재 감정 결합
    • 사용자별 감정 패턴 학습

구현 우선순위

즉시 구현 가능 (Quick Win)

  1. 감정 DB 테이블 생성 (TimescaleDB 하이퍼테이블로)
  2. 간단한 규칙 기반 감정 분석 (키워드 매칭)
  3. 감정 저장 및 조회 API

TimescaleDB 활용 전략

  • 신규 테이블 우선: emotion_readings를 robeing_metrics DB에 하이퍼테이블로 생성
  • 기존 main_db 유지: 프로덕션 DB는 그대로 유지, 시계열만 분리
  • asyncpg 주의사항: interval 바인딩 이슈 대응 필요 (DOCS/troubleshooting/250715_metrics_graph_timebucket_error.md)

중기 목표 (1-2주)

  1. BERT 모델 통합
  2. ONNX 최적화
  3. Temperature Scaling

장기 목표 (1개월+)

  1. 📅 사용자별 감정 패턴 학습
  2. 📅 실시간 감정 모니터링 대시보드
  3. 📅 감정 기반 응답 생성

리소스 요구사항

모델

  • klue/bert-base (400MB)
  • ONNX 변환 모델 (100MB)
  • 추론 시간: CPU 40-80ms, GPU 10-20ms

인프라

  • 추가 메모리: 500MB-1GB
  • DB 스토리지: 사용자당 일 100KB
  • 계산 리소스: CPU 2 cores 권장

주의사항

  1. 프라이버시

    • 원문 텍스트는 해시만 저장
    • 사용자 동의 필요
    • 삭제 권한 보장
  2. 성능

    • 캐싱 적극 활용
    • 배치 처리로 효율화
    • 비동기 처리 필수
  3. 정확도

    • 한국어 특화 모델 필요
    • 지속적인 모니터링
    • 사용자 피드백 수집

결론

rb10508_micro의 감정 시스템을 rb8001로 이식 또는 skill-embedding으로 분리 필요:

  • rb10508_micro에 Bayesian 기반 감정 시스템 구현됨
  • rb8001에 기본 구조만 있고 실제 기능 없음
  • 이식 또는 독립 스킬화 검토 필요