Spaces:
Sleeping
Sleeping
File size: 4,852 Bytes
d3f9826 b6454ba 00dc9b3 d3f9826 00dc9b3 d3f9826 f44c2f6 99eadfa 00dc9b3 99eadfa 00dc9b3 ae3fa50 99eadfa 9eb4c65 00dc9b3 ae3fa50 00dc9b3 5e76f66 00dc9b3 9eb4c65 ae3fa50 9eb4c65 00dc9b3 ae3fa50 00dc9b3 2e513b0 ae3fa50 2e513b0 ae3fa50 9eb4c65 ae3fa50 9eb4c65 ae3fa50 9eb4c65 ae3fa50 2e513b0 f44c2f6 2e513b0 ae3fa50 f44c2f6 ae3fa50 00dc9b3 99eadfa 00dc9b3 99eadfa 00dc9b3 ae3fa50 2e513b0 00dc9b3 ae3fa50 b6454ba 00dc9b3 99eadfa 00dc9b3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | import gradio as gr
import pandas as pd
from datetime import datetime
import logging
# 로그 설정
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def analyze_reviews(file_path, selected_year):
try:
logger.info("엑셀 파일 업로드 시작")
# 엑셀 파일 읽기
df = pd.read_excel(file_path)
logger.info("엑셀 파일 읽기 완료")
# 현재 연도
current_year = 2025
start_year = current_year - 4 # 최근 5년
logger.info(f"데이터 필터링: {start_year}년부터 {current_year}년까지")
# B열이 리뷰 날짜라고 가정하고, 'B' 열의 이름을 '리뷰날짜'로 변경
if '리뷰날짜' not in df.columns:
df.rename(columns={df.columns[1]: '리뷰날짜'}, inplace=True)
# 리뷰 날짜를 datetime으로 변환
df['리뷰날짜'] = pd.to_datetime(df['리뷰날짜'], errors='coerce')
# 최근 5년 데이터 필터링
df_recent = df[df['리뷰날짜'].dt.year >= start_year]
logger.info(f"최근 5년 데이터 필터링 완료: {df_recent.shape[0]}건")
# 년월별 리뷰 건수 계산
logger.info("월별 리뷰 건수 집계 시작")
df_recent['년월'] = df_recent['리뷰날짜'].dt.strftime('%Y-%m')
review_counts = df_recent.groupby('년월').size().reset_index(name='리뷰건수')
logger.info("월별 리뷰 건수 집계 완료")
# 새로운 시트에 저장 (기존 시트가 있으면 대체)
logger.info("새로운 시트 '월별 리뷰건수' 생성 시작")
with pd.ExcelWriter(file_path, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer:
review_counts.to_excel(writer, sheet_name='월별 리뷰건수', index=False)
logger.info("새로운 시트 '월별 리뷰건수' 생성 완료")
# 요청사항 추가 시작
logger.info("선택년 데이터 필터링 및 분석 시작")
# selected_year를 정수로 변환
try:
selected_year = int(selected_year)
logger.info(f"선택한 연도: {selected_year}")
except ValueError:
logger.error("선택한 연도를 정수로 변환하는데 실패했습니다.")
return None
# 선택한 연도로 데이터 필터링
df_selected = df[df['리뷰날짜'].dt.year == selected_year]
logger.info(f"선택한 연도 {selected_year} 데이터 필터링 완료: {df_selected.shape[0]}건")
if df_selected.empty:
logger.warning(f"선택한 연도 {selected_year}에 해당하는 데이터가 없습니다.")
# 빈 데이터프레임을 생성하여 시트에 저장
selected_review_counts = pd.DataFrame(columns=['년월', '리뷰건수'])
else:
# 년월별 리뷰 건수 계산
df_selected['년월'] = df_selected['리뷰날짜'].dt.strftime('%Y-%m')
selected_review_counts = df_selected.groupby('년월').size().reset_index(name='리뷰건수')
logger.info("선택년 월별 리뷰 건수 집계 완료")
# 새로운 시트에 저장 (기존 시트가 있으면 대체)
logger.info("새로운 시트 '선택월별 리뷰건수' 생성 시작")
with pd.ExcelWriter(file_path, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer:
selected_review_counts.to_excel(writer, sheet_name='선택월별 리뷰건수', index=False)
logger.info("새로운 시트 '선택월별 리뷰건수' 생성 완료")
# 요청사항 추가 끝
return file_path
except Exception as e:
logger.error(f"분석 중 오류 발생: {e}")
return None
# 그라디오 인터페이스 구성
def main():
logger.info("그라디오 인터페이스 시작")
with gr.Blocks() as demo:
gr.Markdown("### 리뷰 분석 스페이스")
with gr.Row():
file_input = gr.File(label="원본 엑셀 파일 업로드", file_types=[".xlsx"])
file_output = gr.File(label="분석된 엑셀 파일 다운로드", type="filepath")
with gr.Row():
# 최근 5년을 라디오 버튼으로 선택
current_year = 2025
year_options = [str(year) for year in range(current_year - 4, current_year + 1)] # 최근 5년
year_selection = gr.Radio(label="분석할 연도 선택", choices=year_options, value=str(current_year))
analyze_button = gr.Button("분석")
# 버튼 클릭 시 analyze_reviews 함수 호출, 파일과 선택한 연도 전달
analyze_button.click(fn=analyze_reviews, inputs=[file_input, year_selection], outputs=file_output)
demo.launch()
if __name__ == "__main__":
main()
|