Spaces:
Sleeping
Sleeping
import pandas as pd | |
from collections import Counter | |
import gradio as gr | |
import openpyxl | |
from openpyxl.drawing.image import Image # 이미지 삽입을 위한 모듈 | |
import os # 경로 확인 및 생성용 | |
import re # 특수문자 제거를 위한 정규식 사용 | |
def clean_text(text): | |
# 정규식을 사용하여 특수문자를 제거하되, '-'와 '+'는 제외 | |
return re.sub(r'[^\w\s\-\+]', '', text) | |
def extract_keywords(file): | |
# 엑셀 파일 읽기 | |
df = pd.read_excel(file, engine='openpyxl', header=None) # 첫 번째 행을 헤더로 사용하지 않음 | |
# 열 이름 확인 | |
print("엑셀 열 이름:", df.columns) | |
# 상품명 열에서 D4부터 끝까지 텍스트 추출 (D 열은 index 3이므로 df[3] 사용) | |
product_names = df[3][3:] # D4 셀부터 시작하는 데이터 추출 | |
keywords = [] | |
for name in product_names: | |
if pd.notna(name): # NaN 값 체크 | |
clean_name = clean_text(name) # 특수문자 제거 | |
words = clean_name.split(" ") # 공백 기준으로 단어 분리 | |
keywords.extend(words) | |
# 키워드 빈도수 계산 | |
keyword_count = Counter(keywords) | |
# 데이터프레임으로 변환 | |
result_df = pd.DataFrame(keyword_count.items(), columns=['키워드', '빈도수']) | |
# 빈도수 기준으로 내림차순 정렬 | |
result_df = result_df.sort_values(by='빈도수', ascending=False).reset_index(drop=True) | |
# 파일 저장 경로 설정 | |
output_dir = "results" | |
output_path = os.path.join(output_dir, "키워드_분석_결과_with_logo.xlsx") | |
# 디렉토리 존재 여부 확인 및 생성 | |
if not os.path.exists(output_dir): | |
os.makedirs(output_dir) | |
# 새로운 엑셀 파일 생성 및 이미지 삽입 | |
with pd.ExcelWriter(output_path, engine='openpyxl') as writer: | |
# 엑셀의 첫 3줄을 비워두기 위해 행 인덱스를 3칸 내림 | |
result_df.to_excel(writer, index=False, startrow=3) | |
workbook = writer.book | |
worksheet = workbook.active | |
# 이미지 파일 불러오기 (실제 이미지 경로 지정) | |
logo_path = "ssboost-logo.png" # 실제 이미지 파일 경로 | |
if os.path.exists(logo_path): | |
img = Image(logo_path) | |
# 이미지 크기 조정 (width=140, height=40) | |
img.width = 140 # 너비 설정 | |
img.height = 40 # 높이 설정 | |
# A1 셀에 이미지 삽입 | |
worksheet.add_image(img, "A1") | |
else: | |
print("이미지 파일을 찾을 수 없습니다:", logo_path) | |
return result_df, output_path | |
def keyword_analysis_interface(file): | |
result_df, output_path = extract_keywords(file) | |
return result_df, output_path | |
# Gradio 인터페이스 설정 | |
interface = gr.Interface( | |
fn=keyword_analysis_interface, | |
inputs=gr.File(label="엑셀 파일 업로드"), | |
outputs=[gr.Dataframe(headers=["키워드", "빈도수"]), gr.File(label="결과 엑셀 파일 다운로드")], | |
title="키워드 빈도수 분석기", | |
description="업로드된 엑셀 파일에서 상품명에 대한 키워드를 분석하여 빈도수를 계산하고 엑셀 파일로 결과를 제공합니다." | |
) | |
if __name__ == "__main__": | |
interface.launch() | |