SG34's picture
Update app.py
ff1107a verified
Raw History Blame Contribute Delete
2.57 kB
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()