-
Notifications
You must be signed in to change notification settings - Fork 2
[AI] SISC2-40 [FIX] inference 오류 수정 #83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
The head ref may contain hidden characters: "SISC2-40-AI-\uC11D\uC7AC\uBE48-inference-\uCF54\uB4DC-\uC218\uC815"
Conversation
둘러보기파이프라인의 필수 컬럼과 XAI 증거 형식이 feature_name*/feature_score* 쌍을 요구하도록 변경되었고, XAI 페이로드 생성 로직이 해당 신규 포맷을 중심으로 재구성됨. 추론 모듈에 변경 사항
시퀀스 다이어그램sequenceDiagram
participant Caller as 호출자
participant Pipeline as 파이프라인
participant Inference as 추론모듈
participant XAI as XAI 구성
Caller->>Pipeline: run_signal_transformer / run_xai_report 요청
Pipeline->>Pipeline: _has_required_cols() 검사\n(NEW 포맷 검사 포함)
alt NEW 포맷
Pipeline->>Inference: run_inference() 실행
Inference->>Inference: feature_name/score 계산 및 로그 DataFrame 반환
Inference-->>Pipeline: 확장된 logs_df 전달
Pipeline->>XAI: logs_to_xai_decisions 변환 또는 동적 증거 생성
XAI-->>Pipeline: XAI 페이로드(증거 배열 포함) 반환
Pipeline-->>Caller: XAI 페이로드 반환
else OLD 포맷
Pipeline->>XAI: 기존 증거 구성 경로 사용
XAI-->>Pipeline: XAI 페이로드 반환
Pipeline-->>Caller: XAI 페이로드 반환
end
코드 리뷰 노력 예상치🎯 3 (중간) | ⏱️ ~25분
관련된 가능성 있는 PR
제안된 검토자
시
Pre-merge checks and finishing touches✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
twq110
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
핫픽스 완료
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Nitpick comments (3)
AI/libs/core/pipeline.py (1)
161-193: 신규/구버전 포맷 처리 로직 검증 필요이중 포맷 지원 로직이 잘 설계되었습니다. 신규 포맷은
feature_name과feature_score를 사용하고, 구버전은 순위 기반 가중치를 사용합니다.Line 188의
zip()호출에strict=True매개변수를 추가하여 명시적으로 만들 수 있습니다 (Python 3.10+):- for i, rc in zip((1, 2, 3), rank_contrib): + for i, rc in zip((1, 2, 3), rank_contrib, strict=True):AI/transformer/modules/inference.py (2)
147-151: 코드 스타일 개선 권장한 줄에 세미콜론으로 여러 문장을 작성하는 것보다 각 문장을 별도 줄로 분리하면 가독성이 향상됩니다.
다음과 같이 수정하세요:
if rsi < 30 and macd > 0: - action = "BUY"; buy_p, hold_p, sell_p = 0.65, 0.30, 0.05 + action = "BUY" + buy_p, hold_p, sell_p = 0.65, 0.30, 0.05 elif rsi > 70 and macd < 0: - action = "SELL"; buy_p, hold_p, sell_p = 0.05, 0.30, 0.65 + action = "SELL" + buy_p, hold_p, sell_p = 0.05, 0.30, 0.65 else: - action = "HOLD"; buy_p, hold_p, sell_p = 0.33, 0.34, 0.33 + action = "HOLD" + buy_p, hold_p, sell_p = 0.33, 0.34, 0.33
168-201: 상위 3개 피처 선별 로직이 우수함Min-Max 정규화를 사용한 피처 중요도 계산이 잘 설계되었습니다. NaN 처리, 영역 검증, 무한대 필터링 등 방어적 코딩이 철저합니다.
Line 168의 주석에서 EN DASH(
–)를 HYPHEN-MINUS(-)로 수정하세요:- # === 상위 3개 피처 자동 선별 (히스토리 Min–Max 점수 기준) === + # === 상위 3개 피처 자동 선별 (히스토리 Min-Max 점수 기준) ===
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
AI/libs/core/pipeline.py(6 hunks)AI/tests/quick_db_check.py(1 hunks)AI/transformer/modules/inference.py(7 hunks)
🧰 Additional context used
🪛 Ruff (0.14.3)
AI/transformer/modules/inference.py
147-147: Multiple statements on one line (semicolon)
(E702)
149-149: Multiple statements on one line (semicolon)
(E702)
151-151: Multiple statements on one line (semicolon)
(E702)
168-168: Comment contains ambiguous – (EN DASH). Did you mean - (HYPHEN-MINUS)?
(RUF003)
AI/libs/core/pipeline.py
35-35: Undefined name REQUIRED_OLD
(F821)
41-41: Undefined name REQUIRED_OLD
(F821)
131-131: Consider moving this statement to an else block
(TRY300)
132-132: Do not catch blind exception: Exception
(BLE001)
188-188: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
AI/tests/quick_db_check.py
37-37: String contains ambiguous ℹ (INFORMATION SOURCE). Did you mean i (LATIN SMALL LETTER I)?
(RUF001)
42-42: Do not catch blind exception: Exception
(BLE001)
🔇 Additional comments (8)
AI/tests/quick_db_check.py (1)
1-48: PR 범위가 주요 목적(inference/XAI 컬럼 미스매치)을 벗어남검증 결과:
AI/transformer/modules/inference.py+AI/libs/core/pipeline.py변경은 PR 목적과 정확히 일치합니다. feature_name13, feature_score13 컬럼이 추가되었고, pipeline에서 신규/구버전 형식을 모두 지원하도록 검증 로직이 개선되었습니다.AI/tests/quick_db_check.py의 변경은 context manager 리팩토링(conn 관리 개선)이 맞습니다. 코드 품질 개선으로는 타당하지만, 이 파일은 독립적인 DB 테스트 유틸이며 inference/XAI 컬럼 미스매치 문제와 직접 관련이 없습니다.다른 파일에서 quick_db_check.py를 참조하지 않으므로 변경 자체가 기능을 깨뜨리진 않으나, PR 설명 범위와 변경 범위가 일치하는지 확인해주세요. 필요시 quick_db_check.py 변경은 별도 PR로 분리하는 것을 검토하시기 바랍니다.
AI/libs/core/pipeline.py (3)
55-56: LGTM!UTC 시간 반환 헬퍼 함수가 올바르게 구현되었습니다.
109-112: 컬럼 검증 로직이 올바름신규/구버전 로그 포맷을 모두 허용하는 검증 로직이 적절합니다.
REQUIRED_OLD정의 후 정상 작동할 것입니다.
126-133: LGTM!
_to_float함수에 NaN 처리 로직이 추가되어 더욱 견고해졌습니다. 유틸리티 함수에서의 광범위한 예외 처리는 적절합니다.AI/transformer/modules/inference.py (4)
65-71: LGTM!빈 로그 반환 시 새로운 컬럼 스키마(
feature_name1-3,feature_score1-3)가 일관되게 포함되었습니다.Also applies to: 82-88
153-162: LGTM!가중치 계산 로직이 올바르며,
CLOSE_RAW컬럼 존재 여부를 확인하는 방어적 코딩이 적절합니다.
203-221: LGTM!로그 행 생성이 모든 신규 컬럼을 포함하며, 이전
feature1-3컬럼과의 하위 호환성도 유지합니다.
235-273: LGTM!
logs_to_xai_decisions어댑터 함수가 잘 설계되었습니다. inference 출력을 XAI 입력 형식으로 변환하며, NaN 처리와 명확한 문서화가 훌륭합니다.
| if isinstance(db_cfg, dict): | ||
| with psycopg2.connect(**db_cfg) as conn: | ||
| with conn.cursor() as cur: | ||
| cur.execute("SELECT version();") | ||
| print("✅ 연결 성공:", cur.fetchone()[0]) | ||
| cur.execute("SELECT current_database(), current_user;") | ||
| db, user = cur.fetchone() | ||
| print(f"ℹ️ DB/USER: {db} / {user}") | ||
| else: | ||
| with psycopg2.connect(dsn=str(db_cfg)) as conn: | ||
| with conn.cursor() as cur: | ||
| ... |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Context manager의 변수 스코프 문제 및 DSN 경로 미완성
다음과 같은 심각한 문제들이 있습니다:
-
변수 스코프 문제: Line 31과 39의
with psycopg2.connect(...) as conn:구문에서conn은 with 블록의 지역 변수입니다. Line 28에서 선언한 외부 스코프의conn = None을 덮어쓰지 않기 때문에, finally 블록(line 45-47)에서conn은 항상None입니다. 결과적으로 finally 블록의conn.close()는 절대 실행되지 않습니다. -
DSN 경로 미완성: Lines 39-41의 DSN string 설정 경로는
...만 실행하여 실제로 아무런 테스트도 수행하지 않습니다.
다음 diff를 적용하여 문제를 수정하세요:
-conn = None
try:
if isinstance(db_cfg, dict):
- with psycopg2.connect(**db_cfg) as conn:
- with conn.cursor() as cur:
- cur.execute("SELECT version();")
- print("✅ 연결 성공:", cur.fetchone()[0])
- cur.execute("SELECT current_database(), current_user;")
- db, user = cur.fetchone()
- print(f"ℹ️ DB/USER: {db} / {user}")
+ conn = psycopg2.connect(**db_cfg)
+ with conn.cursor() as cur:
+ cur.execute("SELECT version();")
+ print("✅ 연결 성공:", cur.fetchone()[0])
+ cur.execute("SELECT current_database(), current_user;")
+ db, user = cur.fetchone()
+ print(f"ℹ️ DB/USER: {db} / {user}")
else:
- with psycopg2.connect(dsn=str(db_cfg)) as conn:
- with conn.cursor() as cur:
- ...
+ conn = psycopg2.connect(dsn=str(db_cfg))
+ with conn.cursor() as cur:
+ cur.execute("SELECT version();")
+ print("✅ 연결 성공:", cur.fetchone()[0])
+ cur.execute("SELECT current_database(), current_user;")
+ db, user = cur.fetchone()
+ print(f"ℹ️ DB/USER: {db} / {user}")
except Exception as e:
print("❌ 연결 실패:", repr(e))
finally:
if conn:
conn.close()
print("DB 연결 종료")Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Ruff (0.14.3)
37-37: String contains ambiguous ℹ (INFORMATION SOURCE). Did you mean i (LATIN SMALL LETTER I)?
(RUF001)
🤖 Prompt for AI Agents
In AI/tests/quick_db_check.py around lines 30 to 41, the with-statement usage
shadows the outer conn variable so the finally block never sees a live
connection and the DSN branch is left as a placeholder; fix by not shadowing
conn (assign the result of psycopg2.connect(...) to the outer conn variable
inside a try block instead of using "with ... as conn"), run the same test
queries in the DSN branch as in the dict branch, and keep a finally block that
checks "if conn is not None: conn.close()" to ensure the connection is closed on
all paths.
| print("✅ 연결 성공:", cur.fetchone()[0]) | ||
| cur.execute("SELECT current_database(), current_user;") | ||
| db, user = cur.fetchone() | ||
| print(f"ℹ️ DB/USER: {db} / {user}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
특수 유니코드 문자 사용
ℹ️ (INFORMATION SOURCE) 문자는 일부 터미널 환경에서 렌더링 문제를 일으킬 수 있습니다. 일반적인 ASCII 문자(예: [INFO])를 사용하는 것을 권장합니다.
원하신다면 다음과 같이 수정할 수 있습니다:
- print(f"ℹ️ DB/USER: {db} / {user}")
+ print(f"[INFO] DB/USER: {db} / {user}")📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| print(f"ℹ️ DB/USER: {db} / {user}") | |
| print(f"[INFO] DB/USER: {db} / {user}") |
🧰 Tools
🪛 Ruff (0.14.3)
37-37: String contains ambiguous ℹ (INFORMATION SOURCE). Did you mean i (LATIN SMALL LETTER I)?
(RUF001)
🤖 Prompt for AI Agents
In AI/tests/quick_db_check.py around line 37 replace the special Unicode
information emoji in the print statement with a plain ASCII tag to avoid
terminal rendering issues; change the output to use a standard marker such as
"[INFO] DB/USER: {db} / {user}" (or better, switch to Python's logging.info for
structured logging) so terminals that don't support the ℹ️ glyph won't break.
| with psycopg2.connect(dsn=str(db_cfg)) as conn: | ||
| with conn.cursor() as cur: | ||
| ... | ||
| except Exception as e: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
광범위한 예외 처리
모든 Exception을 catch하는 것은 예상치 못한 에러를 숨길 수 있습니다. DB 연결 테스트 스크립트에서는 허용될 수 있지만, 더 구체적인 예외 타입(예: psycopg2.Error)을 catch하는 것이 좋습니다.
더 구체적인 예외 처리를 원하신다면:
-except Exception as e:
+except psycopg2.Error as e:
print("❌ 연결 실패:", repr(e))Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Ruff (0.14.3)
42-42: Do not catch blind exception: Exception
(BLE001)
🤖 Prompt for AI Agents
In AI/tests/quick_db_check.py around line 42, the code catches a broad Exception
which can hide unexpected errors; replace the broad except with a
database-specific exception (e.g., except psycopg2.Error as e or the DB client’s
specific error class), ensure that the relevant DB exception class is imported
at top, and optionally keep a narrow fallback that re-raises unexpected
exceptions after logging so only DB-related errors are handled here.
구버전 포멧 정리함
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (3)
AI/libs/core/pipeline.py (3)
44-45: 미사용 헬퍼 함수 확인 필요
_utcnow()함수가 정의되었으나 현재 57번 라인에서 주석 처리되어 사용되지 않고 있습니다. 임시로 고정 날짜를 사용 중이라면 향후 서버 배포 시 이 함수를 활성화할 계획인지 확인이 필요합니다.
116-123: 예외 처리 구조 개선 권장함수 로직은 올바르나 코드 구조를 개선할 수 있습니다:
- 120번 라인의 return이 try 블록 내부에 있는데,
else블록으로 이동하는 것이 더 명확합니다.- 122번 라인에서 모든 예외를 포괄적으로 잡고 있습니다. 가능하면
ValueError,TypeError등 구체적인 예외를 명시하는 것이 좋습니다.다음 diff를 적용하여 구조를 개선할 수 있습니다:
def _to_float(v, fallback=0.0) -> float: try: f = float(v) - if pd.isna(f): - return float(fallback) - return f - except Exception: + except (ValueError, TypeError): return float(fallback) + else: + if pd.isna(f): + return float(fallback) + return f
168-181: Evidence 구성 로직 검증 완료신규 XAI 포맷에 맞춰 evidence를 동적으로 구성하는 로직이 올바르게 구현되었습니다. 누락되거나 유효하지 않은 데이터에 대한 방어 로직도 적절합니다.
더 간결한 표현을 원하시면 다음과 같이 리스트 컴프리헨션으로 리팩토링할 수 있습니다:
# === 신규 포맷 전용 evidence === evidence: List[Dict[str, float]] = [] for i in (1, 2, 3): name = row.get(f"feature_name{i}") score = row.get(f"feature_score{i}") # 이름/점수 모두 있어야 추가 if name and str(name).strip() and score is not None and not pd.isna(score): evidence.append({ "feature_name": str(name), "contribution": _to_float(score, 0.0) })
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
AI/libs/core/pipeline.py(6 hunks)
🧰 Additional context used
🪛 Ruff (0.14.3)
AI/libs/core/pipeline.py
121-121: Consider moving this statement to an else block
(TRY300)
122-122: Do not catch blind exception: Exception
(BLE001)
🔇 Additional comments (5)
AI/libs/core/pipeline.py (5)
3-3: LGTM!
Tuple타입 import가run_xai_report함수의 반환 타입 어노테이션에서 올바르게 사용되고 있습니다.
25-32: LGTM!필수 컬럼 정의가 신규 XAI 포맷 요구사항에 맞게 올바르게 업데이트되었습니다.
feature_name1~3과feature_score1~3으로 변경되어 inference 데이터와 XAI 데이터 간의 컬럼 미스매치가 해결되었습니다.
98-102: LGTM!신규 포맷 필수 컬럼에 대한 검증 로직이 올바르게 구현되었습니다. 누락된 컬럼을 명확하게 식별하고 적절한 에러 메시지와 함께 안전하게 처리합니다.
153-158: LGTM!XAI 리포트 생성 전 신규 포맷 필수 컬럼을 검증하는 안전장치가 잘 구현되었습니다. 컬럼 누락 시 명확한 에러 메시지와 함께 안전하게 처리합니다.
126-142: LGTM!함수 시그니처와 docstring이 신규 XAI 포맷 요구사항을 명확하게 반영하고 있습니다. 반환 타입 어노테이션이 정확하며, evidence 배열 구조에 대한 설명도 상세합니다.
inference 데이터 컬럼과 xai 데이터 컬럼 미스매치 수정
Summary by CodeRabbit
새로운 기능
버그 수정