Update app.py
Browse files
app.py
CHANGED
@@ -1,71 +1,96 @@
|
|
1 |
-
# app.py
|
2 |
-
import gradio as gr
|
3 |
-
import pandas as pd
|
4 |
import re
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
def
|
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 |
-
print(f"Error occurred: {str(e)}")
|
57 |
-
return f"Error: {str(e)}"
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
inputs=gr.File(label="Upload Excel File (.xlsx)"),
|
64 |
-
outputs="file",
|
65 |
-
title="Excel Keyword Extractor",
|
66 |
-
description="Upload an Excel file to extract keywords from a column resembling 'D' and calculate their frequencies. The result will be sorted in descending order and saved to a new Excel file."
|
67 |
)
|
68 |
-
interface.launch()
|
69 |
|
|
|
70 |
if __name__ == "__main__":
|
71 |
-
|
|
|
|
|
|
|
|
|
1 |
import re
|
2 |
+
import io
|
3 |
+
import pandas as pd
|
4 |
+
from collections import Counter
|
5 |
+
import gradio as gr
|
6 |
|
7 |
+
def process_excel(file_obj):
|
8 |
+
"""
|
9 |
+
1. 업로드된 엑셀 파일을 읽는다.
|
10 |
+
2. D4 ~ 끝까지의 셀을 순회하면서 키워드를 추출하고,
|
11 |
+
이를 통해 각 키워드별 빈도수를 계산한다.
|
12 |
+
3. 결과를 새 엑셀로 만들어 다운로드 링크를 반환한다.
|
13 |
+
"""
|
14 |
+
|
15 |
+
# 1) 엑셀 읽기
|
16 |
+
df = pd.read_excel(file_obj)
|
17 |
+
|
18 |
+
# D열에서 4번째 행(D4)부터 끝까지 추출(0-based index이므로 df.iloc[3:] 사용)
|
19 |
+
# 만약 컬럼명이 'D'가 아니라면 df.columns로 확인 후 '상품명' 등의 실제 이름 사용
|
20 |
+
if len(df.columns) < 4:
|
21 |
+
return "엑셀 파일에 D열이 존재하지 않습니다."
|
22 |
+
|
23 |
+
product_col = df.iloc[3:, 3] # 0-based이므로 3이 D열
|
24 |
+
|
25 |
+
# 2) 키워드 추출
|
26 |
+
# Counter 객체 생성
|
27 |
+
freq_counter = Counter()
|
28 |
+
|
29 |
+
for cell_value in product_col:
|
30 |
+
if pd.isna(cell_value):
|
31 |
+
continue
|
32 |
+
|
33 |
+
# 문자열로 변환
|
34 |
+
text = str(cell_value)
|
35 |
+
|
36 |
+
# 특수문자 제거
|
37 |
+
text_cleaned = re.sub(r'[^0-9a-zA-Z가-힣\s]', '', text)
|
38 |
+
|
39 |
+
# 공백 분할
|
40 |
+
keywords = text_cleaned.split()
|
41 |
+
|
42 |
+
# 셀 내부 중복 제거
|
43 |
+
keywords_unique = set(keywords)
|
44 |
+
|
45 |
+
# 전체 카운트
|
46 |
+
freq_counter.update(keywords_unique)
|
47 |
+
|
48 |
+
# 빈도수 높은 순(내림차순)으로 정렬
|
49 |
+
sorted_freq = sorted(freq_counter.items(), key=lambda x: x[1], reverse=True)
|
50 |
+
|
51 |
+
# 3) 결과를 새 엑셀로 만들기
|
52 |
+
# A열: 키워드, B열: 빈도수
|
53 |
+
# A4, B4부터라면, 실제 편의를 위해 행을 몇 줄 비워두거나
|
54 |
+
# 단순히 DataFrame을 만들어 header 없이 저장해도 무방함.
|
55 |
+
|
56 |
+
result_data = {
|
57 |
+
"키워드": [item[0] for item in sorted_freq],
|
58 |
+
"빈도": [item[1] for item in sorted_freq]
|
59 |
+
}
|
60 |
+
result_df = pd.DataFrame(result_data)
|
61 |
+
|
62 |
+
# 출력용 엑셀을 메모리에 저장 후 반환
|
63 |
+
output = io.BytesIO()
|
64 |
+
with pd.ExcelWriter(output, engine='openpyxl') as writer:
|
65 |
+
# 만약 A4, B4를 정말 맞춰 쓰려면, startrow=3 사용 가능(0-based)
|
66 |
+
# 예: result_df.to_excel(writer, index=False, startrow=3)
|
67 |
+
result_df.to_excel(writer, index=False, startrow=3, header=False)
|
68 |
+
# A4에는 첫 번째 키워드가, B4에는 빈도수가 들어가도록 (startrow=3)
|
69 |
+
# 다만, header=False로 하면 컬럼명 대신 바로 데이터가 들어감
|
70 |
+
|
71 |
+
output.seek(0)
|
72 |
+
|
73 |
+
# Gradio에서 파일로 반환하기 위해 ("filename.xlsx", bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") 형식
|
74 |
+
return ("keyword_frequency.xlsx", output.getvalue())
|
75 |
|
76 |
+
# Gradio 인터페이스 구성
|
77 |
+
with gr.Blocks() as demo:
|
78 |
+
gr.Markdown("## 상품명에서 키워드 추출하기")
|
79 |
+
excel_input = gr.File(label="엑셀 파일 업로드")
|
80 |
+
download_button = gr.File(label="결과 파일 다운로드")
|
81 |
|
82 |
+
def on_submit(excel_file):
|
83 |
+
# 업로드 파일의 결과 처리를 해서, (파일명, 바이트) 튜플 반환
|
84 |
+
return process_excel(excel_file.name)
|
85 |
|
86 |
+
run_button = gr.Button("분석 및 결과 생성")
|
|
|
|
|
87 |
|
88 |
+
run_button.click(
|
89 |
+
fn=on_submit,
|
90 |
+
inputs=[excel_input],
|
91 |
+
outputs=[download_button]
|
|
|
|
|
|
|
|
|
92 |
)
|
|
|
93 |
|
94 |
+
# 이 스크립트를 실행했을 때 Gradio 서버가 뜨게 하는 부분
|
95 |
if __name__ == "__main__":
|
96 |
+
demo.launch()
|