File size: 3,193 Bytes
d3f9826
 
 
 
 
 
 
 
 
 
de1cc66
d3f9826
 
 
 
de1cc66
 
 
 
 
 
d3f9826
de1cc66
d3f9826
de1cc66
d3f9826
de1cc66
 
 
 
d3f9826
de1cc66
 
 
 
 
d3f9826
de1cc66
 
d3f9826
de1cc66
 
d3f9826
de1cc66
 
d3f9826
 
de1cc66
 
 
 
 
d3f9826
de1cc66
d3f9826
 
 
de1cc66
 
d3f9826
 
 
de1cc66
 
d3f9826
de1cc66
 
 
 
 
 
d3f9826
de1cc66
d3f9826
 
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
import gradio as gr
import pandas as pd
import logging
from datetime import datetime
from io import BytesIO

# 로그 설정
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def analyze_reviews(file):
    logging.info("파일 업로드 시작")
    try:
        # 엑셀 파일 읽기
        df = pd.read_excel(file, engine='openpyxl')
        logging.info("엑셀 파일 읽기 완료")
    except Exception as e:
        logging.error(f"엑셀 파일 읽기 오류: {e}")
        return f"엑셀 파일을 읽는 중 오류가 발생했습니다: {e}"
    
    try:
        # 현재 기준 연도 설정 (2025년 기준)
        current_year = 2025
        start_year = current_year - 3  # 최근 3년

        logging.info("리뷰 날짜 처리 시작")
        # B열에 있는 리뷰 날짜를 datetime 형식으로 변환
        df['리뷰날짜'] = pd.to_datetime(df.iloc[:, 1], errors='coerce')
        # 연도 및 월 필터링
        df_filtered = df[(df['리뷰날짜'].dt.year >= start_year) & (df['리뷰날짜'].dt.year < current_year)]
        logging.info("리뷰 날짜 필터링 완료")

        # 년월별 리뷰 건수 집계
        logging.info("년월별 리뷰 건수 집계 시작")
        df_filtered['년월'] = df_filtered['리뷰날짜'].dt.strftime('%Y-%m')
        review_counts = df_filtered.groupby('년월').size().reset_index(name='리뷰건수')
        logging.info("년월별 리뷰 건수 집계 완료")

        # 새로운 시트에 데이터 작성
        logging.info("새로운 시트 생성 및 데이터 작성 시작")
        with pd.ExcelWriter(file, engine='openpyxl', mode='a') as writer:
            review_counts.to_excel(writer, sheet_name='월별 리뷰건수', index=False, header=['A열', 'B열'])
        logging.info("새로운 시트에 데이터 작성 완료")

        # 결과 파일 저장
        logging.info("결과 파일 저장 시작")
        output = BytesIO()
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            writer.book = pd.ExcelFile(file).book
            for sheet in pd.ExcelFile(file).sheet_names:
                df_sheet = pd.read_excel(file, sheet_name=sheet, engine='openpyxl')
                df_sheet.to_excel(writer, sheet_name=sheet, index=False)
            review_counts.to_excel(writer, sheet_name='월별 리뷰건수', index=False, header=['년월', '리뷰건수'])
        output.seek(0)
        logging.info("결과 파일 저장 완료")

        return output
    except Exception as e:
        logging.error(f"분석 과정 중 오류: {e}")
        return f"분석 과정에서 오류가 발생했습니다: {e}"

# Gradio 인터페이스 구성
with gr.Blocks() as demo:
    gr.Markdown("## 리뷰 분석 스페이스")
    
    with gr.Row():
        file_input = gr.File(label="원본 엑셀 파일 업로드", type="file")
    
    analyze_button = gr.Button("분석")
    output_download = gr.File(label="분석된 엑셀 파일 다운로드")
    
    analyze_button.click(fn=analyze_reviews, inputs=file_input, outputs=output_download)

# 스페이스 실행
if __name__ == "__main__":
    demo.launch()