import gradio as gr import pandas as pd from collections import Counter import matplotlib.pyplot as plt import re import matplotlib.font_manager as fm import urllib.request # Hugging Face Space에서 폰트 다운로드 font_url = "https://huggingface.co/spaces/SG34/Keyword_Analyzer/resolve/main/NotoSansKR-Medium.ttf" font_path = "/tmp/NotoSansKR-Medium.ttf" urllib.request.urlretrieve(font_url, font_path) # 다운로드한 폰트를 matplotlib에 설정 fontprop = fm.FontProperties(fname=font_path) plt.rc('font', family=fontprop.get_name()) def extract_keywords(product_name): # 모델명 제거를 위한 정규표현식 패턴 설정 model_pattern = r'\b[A-Z]{1,3}-\w+\b' # 모델명을 제거하고 남은 텍스트 추출 cleaned_name = re.sub(model_pattern, '', product_name) # 구두점 제거 및 텍스트를 띄어쓰기 기준으로 나누기 cleaned_name = re.sub(r'[^\w\s]', '', cleaned_name) keywords = [word.strip() for word in cleaned_name.split() if word] return keywords def process_file(file, num_keywords): # 엑셀 파일을 읽어오기 df = pd.read_excel(file) # 상품명 열 추출 product_names = df.iloc[2:, 3] # 상품명이 있는 열을 가져옴 # 모든 상품명에서 키워드 추출 keywords = [] for name in product_names: keywords.extend(extract_keywords(name)) # 키워드 빈도수 계산 keyword_counts = Counter(keywords) # 사용자가 선택한 개수만큼 상위 키워드 추출 common_keywords = keyword_counts.most_common(num_keywords) # 키워드 빈도수 그래프 생성 keywords, counts = zip(*common_keywords) plt.figure(figsize=(10, 6)) plt.bar(keywords, counts) plt.title(f'Top {num_keywords} Keywords by Frequency') plt.xlabel('Keywords') plt.ylabel('Frequency') plt.xticks(rotation=45) # 그래프를 저장하고 반환 plt.savefig('keyword_frequency.png') # 결과 출력용 텍스트 생성 result_text = "\n".join([f"{keyword}: {count}" for keyword, count in common_keywords]) return result_text, 'keyword_frequency.png' # Gradio 인터페이스 생성 demo = gr.Interface( fn=process_file, inputs=[ gr.File(label="Upload Excel File"), gr.Dropdown(choices=[10, 20, 30, 40, 50], value=10, label="Number of Top Keywords") ], outputs=[gr.Textbox(label="Top Keywords"), gr.Image(type="filepath", label="Keyword Frequency Graph")] ) if __name__ == "__main__": demo.launch()