Download app.py from Sangwon78/example8: direct link, hf CLI and curl.
- Browser
- Download file 6.26 kB
-
https://huggingface.co/spaces/Sangwon78/example8/resolve/main/app.py
- Command line
-
hf download hf://spaces/Sangwon78/example8/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Sangwon78/example8/resolve/main/app.py
6.26 kB
| import gradio as gr | |
| import pandas as pd | |
| import re | |
| import io | |
| import openpyxl | |
| from openpyxl import Workbook | |
| import tempfile | |
| def remove_special_characters(text: str): | |
| return re.sub(r"[^\w\sㄱ-힣]", "", text) | |
| def extract_keywords(text_list, top_n=3): | |
| combined_text = " ".join(text_list) | |
| combined_text = remove_special_characters(combined_text) | |
| words = combined_text.split() | |
| freq = {} | |
| for w in words: | |
| freq[w] = freq.get(w, 0) + 1 | |
| sorted_words = sorted(freq.items(), key=lambda x: x[1], reverse=True) | |
| keywords = [w[0] for w in sorted_words[:top_n]] | |
| return ", ".join(keywords) | |
| def process_excel(file): | |
| # ----------------------------- | |
| # (기존) 엑셀 읽기 & 기본 처리 | |
| # ----------------------------- | |
| df = pd.read_excel(file.name, header=None) | |
| df.columns = ["고객ID", "리뷰날짜", "리뷰내용", "리뷰점수"] + list(df.columns[4:]) | |
| df["리뷰내용"] = df["리뷰내용"].astype(str).apply(remove_special_characters) | |
| df_use = df[["고객ID", "리뷰날짜", "리뷰내용", "리뷰점수"]] | |
| all_ids = df_use["고객ID"].dropna().unique() | |
| combined_id = ", ".join(map(str, all_ids)) | |
| all_dates = df_use["리뷰날짜"].dropna().unique() | |
| combined_dates = ", ".join(map(str, sorted(all_dates))) | |
| keywords = extract_keywords(df_use["리뷰내용"].tolist()) | |
| df_use["리뷰점수"] = pd.to_numeric(df_use["리뷰점수"], errors='coerce') | |
| score_mean = df_use["리뷰점수"].mean() | |
| # ----------------------------- | |
| # (기존) 새 Workbook에 "기존데이터" 시트 | |
| # ----------------------------- | |
| wb = Workbook() | |
| ws = wb.active | |
| ws.title = "기존데이터" | |
| ws["A1"] = "고객ID" | |
| ws["B1"] = "리뷰날짜" | |
| ws["C1"] = "리뷰내용" | |
| ws["D1"] = "리뷰점수" | |
| for i, row in enumerate(df_use.values, start=2): | |
| ws.cell(row=i, column=1, value=row[0]) | |
| ws.cell(row=i, column=2, value=row[1]) | |
| ws.cell(row=i, column=3, value=row[2]) | |
| ws.cell(row=i, column=4, value=row[3]) | |
| ws["A8"] = combined_id | |
| ws["B8"] = combined_dates | |
| ws["C8"] = keywords | |
| ws["D8"] = score_mean | |
| # ---------------------------------------- | |
| # (추가) A1~K1, A2~K21까지 추출 | |
| # ---------------------------------------- | |
| df_raw = pd.read_excel(file.name, header=None) | |
| # A1~K1 (row=0, col=0~10) | |
| row1 = df_raw.iloc[0, 0:11].fillna('').tolist() | |
| # A2~K21 (row=1~20, col=0~10) | |
| rows2to21 = df_raw.iloc[1:21, 0:11].fillna('') | |
| # H열(=col index=7) 기준 내림차순 정렬 | |
| sorted_rows = rows2to21.sort_values(by=7, ascending=False) | |
| # ---------------------------------------------------- | |
| # (추가) "추가데이터" 시트 | |
| # ---------------------------------------------------- | |
| ws_add = wb.create_sheet("추가데이터") | |
| # A1~K1 | |
| for col_idx, val in enumerate(row1, start=1): | |
| ws_add.cell(row=1, column=col_idx, value=val) | |
| # A2~K21 (원본 순서) | |
| for row_idx, row_data in enumerate(rows2to21.values, start=2): | |
| for col_idx, val in enumerate(row_data, start=1): | |
| ws_add.cell(row=row_idx, column=col_idx, value=val) | |
| # ---------------------------------------------------- | |
| # (추가) "정렬데이터" 시트 (H열 기준 내림차순) | |
| # ---------------------------------------------------- | |
| ws_sorted = wb.create_sheet("정렬데이터") | |
| # A1~K1 | |
| for col_idx, val in enumerate(row1, start=1): | |
| ws_sorted.cell(row=1, column=col_idx, value=val) | |
| # 정렬된 A2~K21 | |
| for row_offset, row_data in enumerate(sorted_rows.values, start=2): | |
| for col_idx, val in enumerate(row_data, start=1): | |
| ws_sorted.cell(row=row_offset, column=col_idx, value=val) | |
| # ------------------------------------------------------------ | |
| # (핵심 수정 포인트) | |
| # 최종 "다운로드" 되는 엑셀 파일에는 "정렬데이터"만 포함시키기 | |
| # ------------------------------------------------------------ | |
| # 지금까지 만든 wb에는 "기존데이터", "추가데이터", "정렬데이터"가 들어있지만 | |
| # 최종 다운로드 파일에는 "정렬데이터" 시트만 들어있도록 새 wb_final을 생성 | |
| wb_final = Workbook() | |
| ws_final = wb_final.active | |
| ws_final.title = "정렬데이터" | |
| # 헤더(A1~K1) | |
| for col_idx, val in enumerate(row1, start=1): | |
| ws_final.cell(row=1, column=col_idx, value=val) | |
| # 정렬된 A2~K21 | |
| for row_offset, row_data in enumerate(sorted_rows.values, start=2): | |
| for col_idx, val in enumerate(row_data, start=1): | |
| ws_final.cell(row=row_offset, column=col_idx, value=val) | |
| # ---------------------------------------------------- | |
| # (기존) 미리보기 DataFrame | |
| # ---------------------------------------------------- | |
| # 여기서는 정렬된 결과만 미리보기 예시 | |
| df_preview_added = pd.DataFrame(sorted_rows.values, columns=[f"Col_{c}" for c in range(1,12)]) | |
| # ---------------------------------------------------- | |
| # (수정) wb_final을 최종 파일로 저장 | |
| # ---------------------------------------------------- | |
| output = io.BytesIO() | |
| wb_final.save(output) # 수정 지점: wb -> wb_final | |
| output.seek(0) | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp: | |
| tmp.write(output.getvalue()) | |
| tmp_path = tmp.name | |
| # Gradio로 반환 | |
| return df_preview_added, tmp_path | |
| def create_app(): | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## 엑셀 파일 업로드 데모") | |
| file_input = gr.File(label="엑셀 파일 업로드", file_types=[".xlsx"]) | |
| generate_button = gr.Button("데이터 추출 및 결과 생성") | |
| output_df = gr.DataFrame(label="처리된 결과 미리보기 (H열 기준 내림차순)") | |
| download_file = gr.File(label="결과 엑셀 다운로드") | |
| def on_click(file): | |
| df_preview, tmp_path = process_excel(file) | |
| return df_preview, tmp_path | |
| generate_button.click( | |
| fn=on_click, | |
| inputs=file_input, | |
| outputs=[output_df, download_file] | |
| ) | |
| return demo | |
| if __name__ == "__main__": | |
| app = create_app() | |
| app.launch() | |