SG34 commited on
Commit
c14f346
·
verified ·
1 Parent(s): 8878ba1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -62
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 extract_keywords(file):
7
- try:
8
- # 엑셀 파일 읽기
9
- df = pd.read_excel(file, engine='openpyxl')
10
- print("Excel file loaded successfully")
11
- print("DataFrame columns:", df.columns) # 이름 확인
12
-
13
- # 열 이름 유연하게 처리
14
- target_column = None
15
- for column in df.columns:
16
- if column.strip().lower() == 'd':
17
- target_column = column
18
- break
19
-
20
- if not target_column:
21
- raise ValueError("No column resembling 'D' found in the uploaded file.")
22
-
23
- product_names = df[target_column]
24
- print(f"Column '{target_column}' data extracted:", product_names.head())
25
-
26
- # 키워드 추출 함수
27
- def process_text(text):
28
- # 특수문자 제거 및 공백으로 분리
29
- words = re.sub(r'[^\w\s]', '', str(text)).split()
30
- return words
31
-
32
- # 키워드와 빈도 계산
33
- keyword_counts = {}
34
- for product_name in product_names.dropna():
35
- keywords = process_text(product_name)
36
- for keyword in set(keywords): # 중복 제거
37
- keyword_counts[keyword] = keyword_counts.get(keyword, 0) + 1
38
-
39
- print("Keyword counts calculated:", keyword_counts)
40
-
41
- # 결과를 데이터프레임으로 변환
42
- result_df = pd.DataFrame(keyword_counts.items(), columns=['Keyword', 'Frequency'])
43
- result_df.sort_values(by='Frequency', ascending=False, inplace=True)
44
-
45
- print("Result DataFrame:")
46
- print(result_df.head())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- # 결과 엑셀 파일로 저장
49
- output_file = "keyword_analysis_result.xlsx"
50
- result_df.to_excel(output_file, index=False, engine='openpyxl')
51
- print(f"Results saved to {output_file}")
 
52
 
53
- return output_file
 
 
54
 
55
- except Exception as e:
56
- print(f"Error occurred: {str(e)}")
57
- return f"Error: {str(e)}"
58
 
59
- # Gradio 인터페이스 정의
60
- def main():
61
- interface = gr.Interface(
62
- fn=extract_keywords,
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
- main()
 
 
 
 
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()