solorpower_crawler/scripts_archive/verify_february_data.py
2026-03-30 13:01:18 +09:00

181 lines
6.3 KiB
Python

"""
2월 데이터 검증 스크립트
5호기(kremc-05), 9호기(nrems-09)의 2월 데이터가 DB에 제대로 저장되었는지 확인
"""
import sys
import os
from datetime import datetime
from dotenv import load_dotenv
# .env 로드
load_dotenv()
# Windows 인코딩 문제 해결
if sys.platform.startswith('win'):
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
# 프로젝트 루트 경로 추가
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
from database import get_supabase_client
def verify_data(plant_id, plant_name):
"""특정 발전소의 2월 데이터 검증"""
print(f"\n{'='*70}")
print(f"🔍 [{plant_name}] 2월 데이터 검증 중...")
print(f"{'='*70}")
client = get_supabase_client()
if client is None:
print("❌ Supabase 연결 실패")
return
# 2월 데이터 범위 설정
now = datetime.now()
year = now.year
start_date = f"{year}-02-01"
if now.month == 2:
end_date = now.strftime("%Y-%m-%d")
else:
# 2월 마지막 날
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
end_date = f"{year}-02-29"
else:
end_date = f"{year}-02-28"
month_str = f"{year}-02"
try:
# 1. 시간별 데이터 확인 (solar_logs)
print(f"\n📊 [Hourly] 시간별 데이터 (solar_logs)")
print(f" 조회 기간: {start_date} ~ {end_date}")
hourly_result = client.table("solar_logs") \
.select("*", count='exact') \
.eq("plant_id", plant_id) \
.gte("created_at", f"{start_date}T00:00:00+09:00") \
.lte("created_at", f"{end_date}T23:59:59+09:00") \
.order("created_at", desc=False) \
.execute()
hourly_count = hourly_result.count if hasattr(hourly_result, 'count') else len(hourly_result.data)
if hourly_count > 0:
print(f" ✅ 총 {hourly_count}건의 시간별 데이터 발견")
# 날짜별 카운트 집계
dates = {}
total_kwh = 0
for record in hourly_result.data:
date_str = record['created_at'][:10]
dates[date_str] = dates.get(date_str, 0) + 1
total_kwh += record.get('today_kwh', 0)
print(f" 📅 {len(dates)}일간의 데이터")
# 처음 3일과 마지막 3일 샘플 표시
sorted_dates = sorted(dates.keys())
print(f"\n [샘플 - 처음 3일]")
for d in sorted_dates[:3]:
print(f" {d}: {dates[d]}")
if len(sorted_dates) > 6:
print(f" ... ({len(sorted_dates) - 6}일 생략) ...")
print(f"\n [샘플 - 마지막 3일]")
for d in sorted_dates[-3:]:
print(f" {d}: {dates[d]}")
print(f"\n 💡 평균 발전량 합계: {total_kwh / len(hourly_result.data):.2f} kWh/시간")
else:
print(f" ⚠️ 시간별 데이터가 없습니다!")
# 2. 일별 데이터 확인 (daily_stats)
print(f"\n📊 [Daily] 일별 데이터 (daily_stats)")
print(f" 조회 기간: {start_date} ~ {end_date}")
daily_result = client.table("daily_stats") \
.select("*", count='exact') \
.eq("plant_id", plant_id) \
.gte("date", start_date) \
.lte("date", end_date) \
.order("date", desc=False) \
.execute()
daily_count = daily_result.count if hasattr(daily_result, 'count') else len(daily_result.data)
if daily_count > 0:
print(f" ✅ 총 {daily_count}건의 일별 데이터 발견")
total_generation = sum(r.get('total_generation', 0) for r in daily_result.data)
avg_generation = total_generation / daily_count if daily_count > 0 else 0
print(f" 📈 2월 총 발전량: {total_generation:.2f} kWh")
print(f" 📈 일평균 발전량: {avg_generation:.2f} kWh")
# 처음 5일과 마지막 5일 샘플 표시
print(f"\n [샘플 - 처음 5일]")
for record in daily_result.data[:5]:
print(f" {record['date']}: {record.get('total_generation', 0):.2f} kWh")
if len(daily_result.data) > 10:
print(f" ... ({len(daily_result.data) - 10}일 생략) ...")
print(f"\n [샘플 - 마지막 5일]")
for record in daily_result.data[-5:]:
print(f" {record['date']}: {record.get('total_generation', 0):.2f} kWh")
else:
print(f" ⚠️ 일별 데이터가 없습니다!")
# 3. 월별 데이터 확인 (monthly_stats)
print(f"\n📊 [Monthly] 2월 월별 데이터 (monthly_stats)")
print(f" 조회 월: {month_str}")
monthly_result = client.table("monthly_stats") \
.select("*") \
.eq("plant_id", plant_id) \
.eq("month", month_str) \
.execute()
if monthly_result.data:
record = monthly_result.data[0]
print(f" ✅ 2월 월별 통계 발견")
print(f" 📈 총 발전량: {record.get('total_generation', 0):.2f} kWh")
print(f" 🕐 업데이트: {record.get('updated_at', 'N/A')}")
else:
print(f" ⚠️ 2월 월별 데이터가 없습니다!")
print(f"\n✅ [{plant_name}] 검증 완료\n")
except Exception as e:
print(f"❌ 검증 중 오류 발생: {e}")
import traceback
traceback.print_exc()
def main():
"""메인 실행 함수"""
plants = [
('kremc-05', '5호기'),
('nrems-09', '9호기')
]
print("\n" + "="*70)
print("🔍 2월 데이터 검증 시작")
print("="*70)
for plant_id, plant_name in plants:
verify_data(plant_id, plant_name)
print("="*70)
print("🎉 모든 검증 완료!")
print("="*70 + "\n")
if __name__ == "__main__":
main()